Problem

Maximum Subarray Sum After Swaps

Learn this problem
infosys logoinfosysOA

Problem statement

You are given an integer array a and an integer k.

You may perform at most k swap operations. In one swap, choose any two indices i and j and swap a[i] with a[j].

After performing at most k swaps, return the maximum possible subarray sum.

Function

maximumSubarraySumAfterSwaps(a: int[], k: int) β†’ int

Examples

Example 1

a = [1,-5,2]k = 1return = 3

Choose the subarray [-5,2] and swap -5 with the outside value 1. The resulting chosen subarray has sum 1 + 2 = 3.

Example 2

a = [4,-10,3,2]k = 1return = 9

Choose the subarray [4,-10,3] and swap -10 with the outside value 2. The subarray sum becomes 4 + 2 + 3 = 9.

Example 3

a = [-2,3,-1]k = 0return = 3

No swaps are allowed, so this is the usual maximum subarray sum.

Constraints

  • 2 <= a.length <= 500
  • 0 <= k <= 500
  • -1000 <= a[i] <= 1000

More infosys problems

drafts saved locally
public int maximumSubarraySumAfterSwaps(int[] a, int k) {
  // write your code here
}
a[1,-5,2]
k1
expected3
checking account