Given an array of integers and a number, find the maximum sum of any subarray of length num. This problem is ideal for demonstrating the sliding window technique, which optimizes nested loops into a single pass.
Example:
maxSubarraySum([2, 6, 9, 2, 1, 8, 5, 6, 3], 3); // Returns 19 (from subarray [8, 5, 6])
function maxSubarraySum(arr, num) {
if (arr.length < num) return null;
let max = -Infinity;
for (let i = 0; i <= arr.length - num; i++) {
let temp = 0;
for (let j = 0; j < num; j++) {
temp += arr[i + j];
}
max = Math.max(max, temp);
}
return max;
}
Explanation:
function maxSubarraySum(arr, num) {
if (arr.length < num) return null;
let max = 0;
let temp = 0;
for (let i = 0; i < num; i++) {
max += arr[i];
}
temp = max;
for (let i = num; i < arr.length; i++) {
temp = temp - arr[i - num] + arr[i];
max = Math.max(max, temp);
}
return max;
}
Explanation:
| Approach | Time Complexity | Space Complexity | Best For | Notes |
|---|---|---|---|---|
| Sliding Window | O(n) | O(1) | Large datasets | Most efficient solution |
| Brute Force | O(n²) | O(1) | Small arrays, simplicity | Easy to implement but slow |
The sliding window technique is a smart way of avoiding recalculation, reducing time complexity from O(n²) to O(n) while using constant space. It’s a powerful technique for optimizing problems involving contiguous sequences.
Honestly i am no one, i've just been coding for 3 years now and i like to document every solutions to every problem i encounter. Extracting as much code snippets and tutorials i can so that if i ever need it again i just have to pop back here and get a quick refresher.
Feel free to me through this learning journey by providing any feedback and if you wanna support me: