hardSliding WindowPattern: Sliding Window
Maximum Subarray Cumulative Levels Solution
Problem Statement
Given an array of integers representing cumulative levels, find the number of subarrays with a cumulative sum within a specified target range.
Examples
Example 1:
Input:[1, 2, 3, 4, 5]
Output:10
Explanation: There are 10 subarrays with cumulative sum within the range: [1], [1, 2], [1, 2, 3], [1, 2, 3, 4], [1, 2, 3, 4, 5], [2, 3, 4, 5], [1, 3, 4], [1, 2, 4], [1, 2, 3, 5], [2, 3, 4]
Example 2:
Input:[-1, 0, 1, 2, 3]
Output:7
Explanation: There are 7 subarrays with cumulative sum within the range: [-1], [0], [1], [2], [3], [0, 1], [-1, 0, 1]
Example 3:
Input:[10, 20, 30, 40, 50]
Output:15
Explanation: There are 15 subarrays with cumulative sum within the range: [10], [20], [30], [40], [50], [10, 20], [20, 30], [30, 40], [40, 50], [10, 20, 30], [20, 30, 40], [30, 40, 50], [10, 20, 30, 40], [20, 30, 40, 50], [10, 20, 30, 40, 50]
Constraints
- The input array will contain only positive integers.
- The target range will be within the bounds of the cumulative sum.
- The input array will not be empty.
Time: O(n^2) Space: O(n)
An optimized approach would utilize the sliding window technique and a prefix sum array to efficiently find the maximum subarray with a cumulative sum within the target range.
Run, Test & Submit Code
Ready to practice this challenge? Launch our interactive compilation environment with compiler validation.
Solve on Interactive WorkspaceTested Solutions
def max_subarray_cumulative_levels(arr, target_min, target_max):
n = len(arr)
prefix_sum = [0] * (n + 1)
max_window_size = 0
for i in range(1, n + 1):
prefix_sum[i] = prefix_sum[i - 1] + arr[i - 1]
left = 0
right = i
curr_window_size = i
while left < right:
curr_sum = prefix_sum[right] - prefix_sum[left]
if curr_sum >= target_min and curr_sum <= target_max:
max_window_size = max(max_window_size, curr_window_size)
right += 1
else:
left += 1
if left == right:
break
return max_window_size