Maximum Subarray Sum of Fixed Length After at Most K Swaps solution and explanation
The problem
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] <= 1091 <= length <= nums.length0 <= k <= nums.length
Approach overview
Problem Overview: You pick a window of fixed length L and may perform at most K swaps to replace elements inside that window with larger elements from outside it. The goal is the largest possible window sum after those swaps. Each swap only helps when the outside value is bigger than the inside value it replaces, so the problem reduces to finding the K best gains.
Approach 1: Brute Force Greedy per Window (O(n² log n) time, O(n) space)
For each starting index, split the array into the window and the rest. Sort the inside values ascending and the outside values descending. Walk both lists together for up to K steps, swapping while the outside value is greater than the inside value, and add each positive difference to the window sum. This is correct because the best swaps always pair the smallest inside values with the largest outside values. It is easy to reason about, but re-sorting for every window wastes work.
Approach 2: Sliding Window with Sorted Gain Tracking (O(n log n) time, O(n) space)
Slide the window one step at a time and keep two ordered multisets: one holding the values inside the window and one holding the values outside. When a value enters or leaves, update the correct structure in O(log n). The useful quantity is the sum of the top K positive gains, where each gain is an outside value minus an inside value that it can replace. Maintain the window sum and the running gain total as you slide, so each window's answer is available without re-sorting. Use a balanced BST, a pair of heaps with lazy deletion, or a Fenwick tree over compressed values. Prefer this approach whenever n is large enough that O(n²) fails.
Recommended for interviews: Explain the brute force first to show you understand why greedy pairing of smallest inside with largest outside is optimal. Then move to the sliding window with ordered structures to show you can maintain the answer incrementally. The brute force shows understanding, but the sliding window version shows skill. Related topics: sliding window, heap / priority queue, greedy.
Solution
Thinking
nis at most300, so every window of lengthlengthcan be evaluated directly. Choosing which indices to swap inside a window grows exponentially withk.The bottleneck is the window boundary. Swapping two elements that are both inside the window, or both outside it, does not change that window's sum. Only an exchange across the boundary does, so the number of useful swaps is at most
min(k,length,n-length).The sum grows only when the incoming value is larger than the outgoing one, so a larger outside value should replace a smaller inside value. After the inside values are sorted in ascending order and the outside values in descending order, the gain of the
j-th swap is non-increasing. Pair from the smallest inside value and stop at the first non-positive gain. The best sum among all windows is the answer.
Fix the window starting at index i. Write the inside values in non-decreasing order a_0 \le a_1 \le cdots and the outside values in non-increasing order b_0 \ge b_1 \ge cdots. After t swaps, the change in the window sum equals the sum of the incoming values minus the sum of the outgoing values. For a fixed t, the optimal choice brings in the t largest outside values and sends out the t smallest inside values, for a change of sum_{j=0}^{t-1}(b_j-a_j). If an incoming value is outside that set, replacing it with a larger unused outside value cannot decrease the sum. If an outgoing value is not one of those t smallest inside values, replacing it with a smaller inside value that has not yet been sent out cannot decrease the sum either.
Because b_j-a_j is non-increasing, the positive terms form a prefix. The number of swaps actually used is the smaller of that prefix length and min(k,length,n-length). Adding the corresponding gains to the original window sum gives the best sum for that starting index, and the answer is the maximum over all starting indices.
The time complexity is O(n^2 log n) and the space complexity is O(n), where n is the length of nums.
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 ansclass Solution {
public long maxSum(int[] nums, int length, int k) {
int n = nums.length;
int maxSwaps = Math.min(k, Math.min(length, n - length));
long ans = Long.MIN_VALUE;
for (int i = 0; i <= n - length; ++i) {
int[] internal = Arrays.copyOfRange(nums, i, i + length);
int[] external = new int[n - length];
System.arraycopy(nums, 0, external, 0, i);
System.arraycopy(nums, i + length, external, i, n - length - i);
Arrays.sort(internal);
Arrays.sort(external);
long total = 0;
for (int v : internal) {
total += v;
}
for (int j = 0; j < maxSwaps; ++j) {
long gain = (long) external[external.length - 1 - j] - internal[j];
if (gain <= 0) {
break;
}
total += gain;
}
ans = Math.max(ans, total);
}
return ans;
}
}class Solution {
public:
long long maxSum(vector<int>& nums, int length, int k) {
int n = nums.size();
int maxSwaps = min(k, min(length, n - length));
long long ans = LLONG_MIN;
for (int i = 0; i <= n - length; ++i) {
vector<int> internal(nums.begin() + i, nums.begin() + i + length);
vector<int> external(nums.begin(), nums.begin() + i);
external.insert(external.end(), nums.begin() + i + length, nums.end());
sort(internal.begin(), internal.end());
sort(external.rbegin(), external.rend());
long long total = accumulate(internal.begin(), internal.end(), 0LL);
for (int j = 0; j < maxSwaps; ++j) {
long long gain = (long long) external[j] - internal[j];
if (gain <= 0) {
break;
}
total += gain;
}
ans = max(ans, total);
}
return ans;
}
};function maxSum(nums: number[], length: number, k: number): number {
const n = nums.length;
const maxSwaps = Math.min(k, length, n - length);
let ans = -Infinity;
for (let i = 0; i <= n - length; ++i) {
const internal = nums.slice(i, i + length).sort((a, b) => a - b);
const external = [...nums.slice(0, i), ...nums.slice(i + length)].sort((a, b) => b - a);
let total = internal.reduce((a, b) => a + b, 0);
for (let j = 0; j < maxSwaps; ++j) {
const gain = external[j] - internal[j];
if (gain <= 0) {
break;
}
total += gain;
}
ans = Math.max(ans, total);
}
return ans;
}func maxSum(nums []int, length int, k int) int64 {
n := len(nums)
maxSwaps := min(k, min(length, n-length))
ans := int64(math.MinInt64)
for i := 0; i <= n-length; i++ {
internal := make([]int, length)
copy(internal, nums[i:i+length])
external := make([]int, 0, n-length)
external = append(external, nums[:i]...)
external = append(external, nums[i+length:]...)
sort.Ints(internal)
sort.Slice(external, func(a, b int) bool { return external[a] > external[b] })
var total int64
for _, v := range internal {
total += int64(v)
}
for j := 0; j < maxSwaps; j++ {
gain := int64(external[j]) - int64(internal[j])
if gain <= 0 {
break
}
total += gain
}
ans = max(ans, total)
}
return ans
}Complexity analysis
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Brute Force Greedy per Window | O(n² log n) | O(n) | Small inputs, verifying correctness |
| Sliding Window with Sorted Gain Tracking | O(n log n) | O(n) | General case, large n (optimal) |
Frequently asked questions
Is Maximum Subarray Sum of Fixed Length After at Most K Swaps easy or hard?
It is a Medium problem with an acceptance rate of about 62.4%, so it is approachable once you see the greedy swap idea. The hard part is maintaining the top K gains efficiently as the window slides. Practice sliding window with heaps to build the skill.
Maximum Subarray Sum of Fixed Length After at Most K Swaps Python and Java solution?
Both languages solve it with a sliding window and ordered containers. Python typically uses heapq with lazy deletion or a sorted list library, while Java uses PriorityQueue or TreeMap for the same role. The logic is identical in both, so choose whichever you can implement cleanly under time pressure.
How to solve Maximum Subarray Sum of Fixed Length After at Most K Swaps in O(n log n)?
Slide a window of length L across the array and keep the inside and outside values in two ordered multisets. Maintain the window sum and the sum of the best K positive gains, where a gain is an outside value minus the inside value it would replace. Update both as elements enter and leave, and record the best total for each window.
What is the best approach for Maximum Subarray Sum of Fixed Length After at Most K Swaps?
The best approach is a sliding window that maintains ordered structures for inside and outside values. It tracks the top K positive swap gains incrementally as the window moves. This runs in O(n log n) time with O(n) space.
What data structure is used in Maximum Subarray Sum of Fixed Length After at Most K Swaps?
The solution uses a sliding window along with ordered structures such as heaps, balanced BSTs, or Fenwick trees. The ordered structures let you quickly find the smallest inside value and largest outside value. Plain arrays alone are not enough for the optimal version.
What is the time complexity of Maximum Subarray Sum of Fixed Length After at Most K Swaps?
The optimal sliding window solution runs in O(n log n) time because each element is inserted and removed from an ordered structure once. A brute force version that re-sorts for every window runs in O(n² log n). Both use O(n) extra space.
Is Maximum Subarray Sum of Fixed Length After at Most K Swaps asked at Google, Amazon, or Meta?
This problem is a Medium-level array and greedy question that appears in contest-style and interview practice sets. Company-specific frequency varies and is not confirmed on FleetCode. Practice the sliding window and heap pattern, since it transfers to many array problems that interviewers ask.