FastPrepMaximum Index-Weighted Sum with Disjoint Swaps

Maximum Index-Weighted Sum with Disjoint Swaps

Visa logoVisa● HardFULLTIMEOA
Learn

Problem statement

For an integer array nums, its score is sum(i * nums[i]) using zero-based indices.

You may choose any number of pairwise-disjoint swaps, including zero. A swap may exchange any two positions, but no position may participate in more than one swap. Return the maximum attainable score.

Function

maxIndexWeightedSum(nums: int[]) → long

Examples

Example 1

nums = [2,1,4,3]return = 20

Swapping positions 0 and 1 and positions 2 and 3 produces [1,2,3,4] with score 20.

Example 2

nums = [-1,5,2]return = 12

Swapping positions 1 and 2 gives [-1,2,5], whose score is 12.

Constraints

  • 1 <= nums.length <= 18.
  • -1000000 <= nums[i] <= 1000000.
  • The answer fits a signed 64-bit integer.

More Visa problems

See Visa hiring insights
public long maxIndexWeightedSum(int[] nums) {
    // Write your code here.
}
nums[2,1,4,3]
expected20
Checking account…