We run the inner while loop as long as the window is valid, which is the condition (windowSum >= target). Won’t this give erroneous results for arrays where there is no sum that equals target?
Sum should be at least target. I misread the question. My bad.
The above solution won’t work for this input
nums = [84,-37,32,40,95], target = 167.
Working code:
public class Solution {
public int ShortestSubarray(int nums, int k) {
int n = nums.Length;
long[] P = new long[n+1];
for (int i = 0; i < n; i++) {
P[i+1] = P[i] + nums[i];
}
int ans = n + 1;
List<int> monoq = new List<int>();
for (int y = 0; y < P.Length; y++) {
while (monoq.Count > 0 && P[y] <= P[monoq[monoq.Count - 1]]) {
monoq.RemoveAt(monoq.Count - 1);
}
while (monoq.Count > 0 && P[y] >= P[monoq[0]] + k) {
int currLen = y - monoq[0];
monoq.RemoveAt(0);
ans = Math.Min(ans, currLen);
}
monoq.Add(y);
}
return ans < n+1 ? ans : -1;
}
}
The template in Javascript for this chapter isn’t Javascript. Could you update it, please?