Talentd
FleetCode

3430. Maximum and Minimum Sums of at Most Size K Subarrays

Hard25.9% acceptance

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 <= 80000
  • 1 <= k <= nums.length
  • -106 <= nums[i] <= 106

Hints open one at a time

Hint 1
Use a monotonic stack.
Hint 2
How can we calculate the number of subarrays where an element is the largest?
Hint 3
Enforce the condition on size too.
16:59
Still stuck?Read the written solution, or watch a walkthrough.
Open solution
Loading editor…
1class Solution:
2 def minMaxSubarraySum(self, nums: List[int], k: int) -> int:
3
Starter codePython 3Spaces: 4
Examples
Input
[1,2,3]
2
Input
[1,-3,1]
2
Your code is saved on this device.Solution