0% completed
I am comparing this problem to what I see on leetcode for 643. Maximum Average S...
Perry Robinson
Feb 18, 2022
I am comparing this problem to what I see on leetcode for 643. Maximum Average Subarray I. When you have to account for negative numbers, this solution in the course does not work. How do we modify our solution to make it work with negative numbers?
2
0
Comments
Carlos Rueda4 years ago
I think that a good solution would be to add an extra conditional for when window_end == k-1, and assign the current sum to max_sum. With that you have a start point to compare and it should work even with negative numbers. You would need to modify the exisiting if stat...
Albert Leung4 years ago
No, the issue is that if your subarray is [-1] with window size 1, you're not going to get the correct solution because your average will be -1.
In that case, 0 always > -1. In python, should set window_sum to -sys.maxsize - 1
Alok Saini3 years ago
problem is not negative numbers, but the fact that we are intializing the max sum as 0, instead of doing that u can intialize that with the first window sum, that will work even in case of negative numbers
Alok Saini3 years ago
carlos solution is also good but it introduce one more condition
aj 3 years ago
It could also be solved by initializing your sum/avg with least possible value of the type you chose.
Abdullah AlKheshen2 years ago
For those who're struggling with this:
I code in C++, I was trying to initialize the double max_average by DBL_MIN since max_average is double. I turned out that I have to initialize it by INT_MIN instead.
The solution would look something like this:
class Solution ...
On this page