Logo
IconChallenge
Icon
IconProblem
IconSolutions
IconSubmissions

Maximize Alternating Sum Using Swaps

XPChallenge Points: 30
levelLevel: Hard

You are given an integer array nums and a 2D integer array swaps, where each element swaps[i] = [pi, qi] represents a pair of indices in nums.
For every pair [pi, qi], you are allowed to swap the elements at indices pi and qi.
You can perform these swaps any number of times and in any order.
Your goal is to maximize the alternating sum of the array nums, where:
alternating sum=nums[0]−nums[1]+nums[2]−nums[3]+…
Return the maximum possible alternating sum you can achieve after performing the swaps optimally.

Example 1:

Input: nums = [4, 7, 3, 9] swaps = [[0, 2], [1, 3]]

Output: -9

Example 2:

Input: nums = [5, 1, 8] swaps = [[0, 1]]

Output: 12

to Continue
like
dislike

Accepted:

Submission:

IconReport an issue
Icon
IconCode
IconYou need toto run or submitYou need toto run or submit
IconTest Case
IconTest Result