Problem · Array

Maximum Weighted Sum with Disjoint Adjacent Swaps

Learn this problem
MediumMicrosoft logoMicrosoftINTERNOA
See Microsoft hiring insights

Problem statement

Given a non-empty integer array arr, you may swap adjacent elements. Each array element may participate in at most one swap, so the chosen adjacent swaps cannot overlap.

After performing any valid set of swaps, define the weighted sum as sum(arr[i] * (i + 1)) over all zero-based indices i.

Return the maximum weighted sum obtainable. The returned value is a signed 64-bit integer.

Function

maxWeightedSum(arr: int[]) → long

Examples

Example 1

arr = [1,3,2]return = 14

Swap the adjacent values 3 and 2 to obtain [1, 2, 3]. Its weighted sum is 1 * 1 + 2 * 2 + 3 * 3 = 14.

Example 2

arr = [4,2,5,1]return = 33

Swap both non-overlapping pairs to obtain [2, 4, 1, 5]. The weighted sum is 2 + 8 + 3 + 20 = 33.

Constraints

  • 1 <= arr.length <= 100000
  • -1000000000 <= arr[i] <= 1000000000

More Microsoft problems

drafts saved locally
public long maxWeightedSum(int[] arr) {
    // write your code here
}
arr[1,3,2]
expected14
checking account