I am trying 907. Sum of Subarray Minimums on Leetcode.
I keep getting this error:
Line 1034: Char 9: runtime error: reference binding to null pointer of type 'int' (stl_vector.h)
SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior /usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/stl_vector.h:1043:9
Here is what I tried (I understand it is very naive and will most probably TLE, but I would also like to know what is wrong such that it doesnt work) :-
class Solution {
public:
int sumSubarrayMins(vector<int>& arr) {
vector<int> ans;
int sum =0;
int mn=0;
int m = 1000000007;
int n = arr.size();
for(int i = 0 ; i<n; i++){
for(int j = i; j<n; j++){
for(int k = i; k<j; k++){
ans.push_back(arr[k]);
}
sort(ans.begin(), ans.end());
mn = ans[0];
sum = sum + mn;
ans.clear();
}
}
return sum%m;
}
};
What is happening?
On the first iteration,
ans
has no elementsi = 0
j = i
(j = 0
)Then no elements will be pushed to ans
because i < j
is false.
Therefore, mn = ans[0];
is invalid out-of-range access because ans
still has no elements.