Maximum Subarray Sum After at Most K Swaps Problem
Description
LeetCode Problem 3962.
You are given an integer array nums and an integer k.
You are allowed to perform at most k swap operations on the array.
In one swap operation, you may choose any two indices i and j and swap nums[i] and nums[j].
Return an integer denoting the maximum possible subarray sum after performing the swaps.
Example 1:
Input: nums = [1,-1,0,2], k = 1
Output: 3
Explanation:
- We can swap on indices 1 and 3, resulting in the array [1, 2, 0, -1].
- The subarray [1, 2] has a sum of 3, which is the maximum possible subarray sum after at most k = 1 swap.
Example 2:
Input: nums = [4,3,2,4], k = 2
Output: 13
Explanation:
The maximum possible subarray sum after at most k = 2 swaps is the sum of the entire array, which is 13.
Example 3:
Input: nums = [-1,-2], k = 0
Output: -1
Explanation:
- k = 0 swaps are allowed.
- The possible subarrays are [-1], [-2], and [-1, -2], with sums -1, -2, and -3 respectively.
- Among these sums, the maximum is -1.
Constraints:
1 <= nums.length <= 1500-10^5 <= nums[i] <= 10^50 <= k <= nums.length
Solution
Approach: Enumerate Subarrays + Binary Indexed Trees
For a fixed subarray [l, r], a swap should exchange one of its elements with an element outside it. The best use of t swaps takes the t smallest values inside and replaces them with the t largest values outside. Writing a_1 <= a_2 <= ... for the inside values and b_1 >= b_2 >= ... for the outside values, the gain of the i-th swap is b_i - a_i, which only shrinks as i grows. So we do swaps while b_i > a_i, up to k of them and at most min(length, n - length).
Enumerate l, then extend r one element at a time, moving nums[r] from the outside to the inside. Keep two Fenwick trees over the compressed values (one for the inside, one for the outside), each storing counts and sums, so we can find the j-th smallest value and the sum of the j smallest values in O(log n). The number of useful swaps p changes only slightly when r moves, so we keep it in a variable and nudge it up or down while the condition b_{p+1} > a_{p+1} (or b_p <= a_p) says so. The candidate for [l, r] is the subarray sum plus the sum of the p largest outside values minus the sum of the p smallest inside values.
Complexity: time O(n^2 log n), space O(n).
class Solution:
def maxSum(self, nums: List[int], k: int) -> int:
n = len(nums)
vals = sorted(set(nums))
V = len(vals)
rank = {v: i + 1 for i, v in enumerate(vals)}
rk = [rank[x] for x in nums]
LOG = 1
while (1 << LOG) <= V:
LOG += 1
def update(cnt, sm, i, dc, ds):
while i <= V:
cnt[i] += dc
sm[i] += ds
i += i & -i
# value of the j-th smallest (1-based) in the tree
def kth(cnt, j):
pos = 0
for b in range(LOG, -1, -1):
nxt = pos + (1 << b)
if nxt <= V and cnt[nxt] < j:
pos = nxt
j -= cnt[nxt]
return vals[pos]
# sum of the j smallest values in the tree
def smallest_sum(cnt, sm, j):
pos = 0
acc = 0
for b in range(LOG, -1, -1):
nxt = pos + (1 << b)
if nxt <= V and cnt[nxt] < j:
pos = nxt
j -= cnt[nxt]
acc += sm[nxt]
return acc + j * vals[pos] if j > 0 else acc
full_cnt = [0] * (V + 1)
full_sum = [0] * (V + 1)
for i in range(n):
update(full_cnt, full_sum, rk[i], 1, nums[i])
total = sum(nums)
ans = -(1 << 62)
for l in range(n):
in_cnt = [0] * (V + 1)
in_sum = [0] * (V + 1)
out_cnt = full_cnt[:]
out_sum = full_sum[:]
s = 0
p = 0
for r in range(l, n):
x = nums[r]
update(in_cnt, in_sum, rk[r], 1, x)
update(out_cnt, out_sum, rk[r], -1, -x)
s += x
c = r - l + 1
out = n - c
cap = min(k, c, out)
p = min(p, cap)
# a_i: i-th smallest inside, b_i: i-th largest outside
while p < cap and kth(out_cnt, out - p) > kth(in_cnt, p + 1):
p += 1
while p > 0 and kth(out_cnt, out - p + 1) <= kth(in_cnt, p):
p -= 1
cand = s
if p > 0:
cand += (total - s - smallest_sum(out_cnt, out_sum, out - p)) - smallest_sum(in_cnt, in_sum, p)
if cand > ans:
ans = cand
return ans