Maximum Subarray Sum of Fixed Length After at Most K Swaps Problem
Description
LeetCode Problem 4087.
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-10^9 <= nums[i] <= 10^91 <= length <= nums.length0 <= k <= nums.length
Solution
Approach: Try Every Window
Fix the window [i, i + length - 1]. Sort the values inside ascending as a0 <= a1 <= ... and the values outside descending as b0 >= b1 >= .... Each swap trades one inside value for one outside value, and t swaps are best spent bringing in the t largest outside values and pushing out the t smallest inside values.
The gains b_j - a_j never increase with j, so the useful swaps form a prefix. Take gains while they are positive, using at most min(k, length, n - length) swaps. Adding them to the window sum gives the best sum for this window, and the answer is the maximum over all windows.
Complexity: O(n2 log n) time (n windows, each sorting O(n) values) and O(n) space.
from math import inf
class Solution:
def maxSum(self, nums: List[int], length: int, k: int) -> int:
n = len(nums)
max_swaps = min(k, length, n - length)
ans = -inf
for i in range(n - length + 1):
internal = sorted(nums[i : i + length])
external = sorted(nums[:i] + nums[i + length :], reverse=True)
total = sum(internal)
for j in range(max_swaps):
gain = external[j] - internal[j]
if gain <= 0:
break
total += gain
ans = max(ans, total)
return ans