Problem link - https://leetcode.com/problems/maximum-average-subarray-i/
class Solution
{
public:
double findMaxAverage(vector<int>& nums, int k)
{
deque<pair<int,int>> d; //deque since its a sliding window problem
vector<double> ans; //to return answer
double avg;
double sum=0;
int n=nums.size();
for(int i=0;i<n;i++)
{
if(!d.empty() && d.front().second<=(i-k)) //out of window size
{
avg=sum/k;
ans.push_back(avg); //push the average of k elements in answer vector
sum=sum-d.front().first; //remove the sum of first element when moving to next
d.pop_front(); //remove front element of deque
}
d.push_back(make_pair(nums[i],i)); //push current element in deque
sum=sum+d.back().first; //add it to sum
}
return *max_element(ans.begin(), ans.end()); //return maximum average of subarray
}
};
I was trying to solve leetcode problem 643 maximum average subarray I , which is an easy problem based on slididng window approach.
I wrote the code and got runtime error saying "Line 811: Char 16: runtime error: reference binding to null pointer of type 'double' (stl_iterator.h) SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior /usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c"
Can anyone please help with this ? Thanks in advance.