Hint: Update sum by adding new and removing old element [OK]
Common Mistakes:
Not subtracting the element leaving the window
Incorrect initial sum calculation
Updating maxSum incorrectly
4. Identify the bug in the following sliding window code that finds the maximum sum of subarrays of size k:
int maxSum = 0;
int windowSum = 0;
for(int i = 0; i <= k; i++) {
windowSum += arr[i];
}
maxSum = windowSum;
for(int i = k; i < arr.length; i++) {
windowSum += arr[i] - arr[i - k];
if(windowSum > maxSum) {
maxSum = windowSum;
}
}
System.out.println(maxSum);
medium
A. The first loop should run from i = 0 to i < k, not i <= k
B. maxSum should be initialized to Integer.MIN_VALUE
C. The second loop should start from i = k + 1
D. windowSum should be reset to 0 before the second loop
Solution
Step 1: Check the first loop boundary
The first loop runs i from 0 to k inclusive, which sums k+1 elements causing out-of-bounds error.
Step 2: Correct loop boundary
The loop should run from 0 to less than k to sum exactly k elements.
Final Answer:
The first loop should run from i = 0 to i < k, not i <= k -> Option A
Quick Check:
Loop boundary off by one causes error [OK]
Hint: Use < k, not <= k, for k elements [OK]
Common Mistakes:
Using <= k causes array index out of bounds
Incorrect initialization of maxSum
Wrong start index in second loop
5. Given an array of integers, write a Java method using the sliding window technique to find the length of the longest subarray with sum less than or equal to a given value target. Which approach correctly solves this problem?
hard
A. Sort the array and use binary search to find subarrays with sum ≤ target
B. Use two pointers to expand and shrink the window, updating max length when sum ≤ target
C. Use nested loops to check all subarrays and track the longest valid one
D. Use a stack to store sums and pop when sum exceeds target
Solution
Step 1: Understand the problem constraints
We want the longest subarray with sum ≤ target, which requires dynamic window size.
Step 2: Apply sliding window with two pointers
Use two pointers to expand the window adding elements, shrink from left when sum > target, track max length.
Final Answer:
Use two pointers to expand and shrink the window, updating max length when sum ≤ target -> Option B