3725. Maximum And Minimum Sums Of At Most Size K Subarrays¶
3725. Maximum and Minimum Sums of at Most Size K Subarrays
Hard
You are given an integer array nums and a positive integer k. Return the sum of the maximum and minimum elements of all subarrays with at most k elements.
Example 1:
Input: nums = [1,2,3], k = 2
Output: 20
Explanation:
The subarrays of nums with at most 2 elements are:
| Subarray | Minimum | Maximum | Sum |
|---|---|---|---|
[1] | 1 | 1 | 2 |
[2] | 2 | 2 | 4 |
[3] | 3 | 3 | 6 |
[1, 2] | 1 | 2 | 3 |
[2, 3] | 2 | 3 | 5 |
| Final Total | 20 |
The output would be 20.
Example 2:
Input: nums = [1,-3,1], k = 2
Output: -6
Explanation:
The subarrays of nums with at most 2 elements are:
| Subarray | Minimum | Maximum | Sum |
|---|---|---|---|
[1] | 1 | 1 | 2 |
[-3] | -3 | -3 | -6 |
[1] | 1 | 1 | 2 |
[1, -3] | -3 | 1 | -2 |
[-3, 1] | -3 | 1 | -2 |
| Final Total | -6 |
The output would be -6.
Constraints:
1 <= nums.length <= 800001 <= k <= nums.length-106 <= nums[i] <= 106
Solution¶
class Solution {
public long minMaxSubarraySum(int[] nums, int k) {
int n = nums.length;
long[] LMax = new long[n];
long[] RMax = new long[n];
Deque<Integer> stack = new ArrayDeque<>();
for(int i = 0; i < n; i++) {
while(!stack.isEmpty() && nums[stack.peek()] <= nums[i]) stack.pop();
if(stack.isEmpty()) LMax[i] = i + 1;
else LMax[i] = i - stack.peek();
stack.push(i);
}
stack = new ArrayDeque<>();
for(int i = n - 1; i >= 0; i--) {
while(!stack.isEmpty() && nums[stack.peek()] < nums[i]) stack.pop();
if(stack.isEmpty()) RMax[i] = (long) (n - i);
else RMax[i] = stack.peek() - i;
stack.push(i);
}
long[] LMin = new long[n];
long[] RMin = new long[n];
stack = new ArrayDeque<>();
for(int i = 0; i < n; i++) {
while(!stack.isEmpty() && nums[stack.peek()] >= nums[i]) stack.pop();
if(stack.isEmpty()) LMin[i] = i + 1;
else LMin[i] = i - stack.peek();
stack.push(i);
}
stack = new ArrayDeque<>();
for (int i = n - 1; i >= 0; i--) {
while(!stack.isEmpty() && nums[stack.peek()] > nums[i]) stack.pop();
if(stack.isEmpty()) RMin[i] = (long) (n - i);
else RMin[i] = stack.peek() - i;
stack.push(i);
}
long ans = 0;
for(int i = 0; i < n; i++) ans += nums[i] * solve(LMax[i], RMax[i], k) + nums[i] * solve(LMin[i], RMin[i], k);
return ans;
}
public long solve(long L, long R, int k) {
if(L <= 0 || R <= 0) return 0;
long total = 0;
long X0 = (long)k - R;
long leftCnt = 0;
if(X0 >= 0) leftCnt = Math.min(L, X0 + 1);
total += (long) R * leftCnt;
long startX = leftCnt;
long endX = L - 1;
if(startX <= endX) {
long realEnd = Math.min(endX, (long)k - 1);
if(startX <= realEnd) {
long count = realEnd - startX + 1;
long a = startX;
long b = realEnd;
long sumX = (b * (b + 1) / 2) - ((a - 1) * a / 2);
long temp = (long)k * count - sumX;
total += temp;
}
}
return Math.max(total, 0);
}
}
Complexity Analysis¶
- Time Complexity: O(?)
- Space Complexity: O(?)
Explanation¶
[Add detailed explanation here]