spiralgo / algorithms

We voluntarily solve algorithm problems on this repo.
24 stars 7 forks source link

644. Maximum Average Subarray II #381

Closed ErdemT09 closed 3 years ago

ErdemT09 commented 3 years ago

Resolves: #240

Algorithm:

The problem here is pretty similar to other binary search problems we had like #369 and #368. We pick some target value, try to find if there is some subarray whose length ≥ k that at least has the target value as average. If it does, we can look for higher values. Else, we need to look for lower values.

While looking if there is such a subarray, we look for differences between averages. If s_i is equal to sum of all elemenets up to some index i, a subarray with average v up to that would have the sum i·v. s_i-i·v - s_j-j·v ≥ 0 would prove that there is a subarray of length i-j that has an average ≥ v. Since the first term also includes the second term in its total, we have to subtract it to get the difference from the average subarray. Finding some j, i-j ≥ k would imply that such a subarray exists.