Talentd
FleetCode

4087. Maximum Subarray Sum of Fixed Length After at Most K Swaps

Medium66.2% acceptancePremium elsewhere, free here

You are given an integer array nums and two integers length and k.

You may perform at most k swap operations on nums.

In one swap operation, you may choose two distinct indices i and j and swap nums[i] and nums[j].

Return the maximum possible sum of a subarray of length exactly length after performing the swaps.

Example 1:

Input: nums = [1,-1,0,2], length = 2, k = 1

Output: 3

Explanation:

  • Swap the elements at indices 1 and 3, resulting in [1, 2, 0, -1].
  • The subarray [1, 2] has length 2 and sum 3.
  • No subarray of length 2 can have a larger sum, since 1 and 2 are the two largest elements.

Example 2:

Input: nums = [4,3,2,4], length = 3, k = 2

Output: 11

Explanation:

  • Swap the elements at indices 2 and 3, resulting in [4, 3, 4, 2].
  • The subarray [4, 3, 4] has length 3 and sum 11.
  • This is the sum of the three largest elements, so no larger answer is possible. Only one swap is needed.

Example 3:

Input: nums = [-1,-2], length = 2, k = 0

Output: -3

Explanation:

No swaps are allowed. The only subarray of length 2 is [-1, -2], whose sum is -3.

Constraints:

  • 1 <= nums.length <= 300
  • -109 <= nums[i] <= 109
  • 1 <= length <= nums.length
  • 0 <= k <= nums.length
Still stuck?Read the written solution.
Open solution
Loading editor…
1class Solution:
2 def solve(self):
3 pass
4
Starter codePython 3Spaces: 4
Examples

No sample inputs for this problem yet. The examples in the statement show the format.

Your code is saved on this device.Solution