When I originally did the solution without reading the answer, I expanded the window size until I found a sum that was greater than or equal to S. My solution completed around 3.6s on average. The answer algorithm uses the biggest window and shrinks, searching for the smallest window length possible with an answer greater than S. When I ran the answer solution, it completed around 3.9s on average.
Can you help me understand what shrinking the window optimizes for compared to growing?
Here is my growing solution:
public static int findMinSubArray(int S, int[] arr) {
int solutionLength = 0;
boolean found = false;
for (int windowSize = 1; windowSize < arr.length; windowSize++) {
if(found) {
break;
}
int windowStart = 0;
int windowSum = 0;
for (int windowEnd = 0; windowEnd < arr.length; windowEnd++) {
windowSum += arr[windowEnd];
if(windowEnd >= windowSize - 1) {
if(windowSum >= S) {
solutionLength = windowSize;
found = true;
break;
}
windowSum -= arr[windowStart];
windowStart++;
}
}
}
return solutionLength;
}
Is my solution with growing the window too optimistic, whereas shrinking the window is likely to find any solution faster given larger data sets?