4th code
/**
* @param {number[]} nums
* @param {number[][]} swaps
* @return {number}
*/
var maxAlternatingSum = function(nums, swaps) {
let drimolenta = [...nums];
const n = nums.length;
const parent = Array(n).fill(0).map((_, i) => i);
const find = (x) => parent[x] === x ? x : (parent[x] = find(parent[x]));
const union = (x, y) => parent[find(x)] = find(y);
for (let [a, b] of swaps) union(a, b);
const components = {};
for (let i = 0; i < n; i++) {
const root = find(i);
if (!components[root]) components[root] = [];
components[root].push(i);
}
const result = Array(n);
for (let group of Object.values(components)) {
const evenIndices = [];
const oddIndices = [];
for (let idx of group) {
if (idx % 2 === 0) evenIndices.push(idx);
else oddIndices.push(idx);
}
const numbers = group.map(i => drimolenta[i]);
numbers.sort((a, b) => b - a); // descending
// Assign largest numbers to even indices first
let ei = 0, oi = 0, ni = 0;
while (ei < evenIndices.length && ni < numbers.length) {
result[evenIndices[ei]] = numbers[ni++];
ei++;
}
while (oi < oddIndices.length && ni < numbers.length) {
result[oddIndices[oi]] = numbers[ni++];
oi++;
}
}
let altSum = 0;
for (let i = 0; i < n; i++) {
altSum += (i % 2 === 0 ? 1 : -1) * result[i];
}
return altSum;
};
Join👇
@leetcode_cp
@leetcode_cp
Post #244
67