Maximum Weighted Sum with Disjoint Adjacent Swaps
Updated
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[]) → longExamples
Example 1
arr = [1,3,2]return = 14Swap 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 = 33Swap both non-overlapping pairs to obtain [2, 4, 1, 5]. The weighted sum is 2 + 8 + 3 + 20 = 33.
Example 3
arr = [2,1,4,3]return = 30Swap arr[0] with arr[1] and arr[2] with arr[3]. The two swaps share no element, so both are allowed, and the array becomes [1, 2, 3, 4]. The weighted sum is 1 * 1 + 2 * 2 + 3 * 3 + 4 * 4 = 30. Making only one of the two swaps gives 29, and swapping the middle pair 4 and 1 gives 25, so 30 is the largest.
Constraints
1 <= arr.length <= 100000-1000000000 <= arr[i] <= 1000000000
More Microsoft Online Assessment questions
- Maximum Score with Prime JumpsOA · Seen Dec 2026
- Minimum Non-Adjacent Selection CapabilityOA · Seen Dec 2026
- Authentication SystemOA · Seen Nov 2026
- Maximum String OperationsOA · Seen Nov 2026
- Minimum Cost to Process Priority TasksOA · Seen Nov 2026
- Most Visited Sprint MarkerOA · Seen Nov 2026
- Maximum Escape Game ScoreOA · Seen Nov 2026
- Count Subarrays with a Perfect-Square ProductOA · Seen Nov 2026
- Maximum Interactive Team SizeOA · Seen Nov 2026
- Maximize Pipeline Throughput Under a Scaling BudgetOA · Seen Nov 2026
Similar questions at other companies
- Maximum Beauty by DeletionsMeesho · OA
- Card Game: Best First-Player ScoreShopify · OAShopify interview questions
- Maximum Game Score with Fixed Forward JumpsStripe · OAStripe interview questions
- 0/1 KnapsackConfluent · OAConfluent interview questions
- Minimum Cost to Tile a Strip with Widths 1, 2, and 3Infosys · OAInfosys interview questions
- Maximum Subarray SumStraive · OA
- Longest Increasing Price SubsequenceOpenAI · OAOpenAI interview questions
- Lowest-Cost Shirt Color ScheduleElevenLabs · OAElevenLabs interview questions
- Maximum Game Board ScoreJP Morgan Chase · OAJP Morgan Chase interview questions
- API Bandwidth AllocationArista Networks · OAArista Networks interview questions