TGViewer
Data Science Data Science @datascienceofficial · 359 subscribers
Post #394 14
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
More from @datascienceofficial
  1. Oct 11, 2026🧠 Data Science Skill: Turn Messy Business Data Into Decisions Real data science is not on…
  2. Oct 10, 2026You can connect or follow me on Linked[in] https://www.linkedin.com/in/subarno-roy-3b22513…
  3. Oct 10, 2026Daily High-Accuracy Quotex Signals ✅ ​ ​Our signals focus on key price action levels, tren…
  4. Oct 9, 2026🚨 Earn Passive Money Easily 🚨 Since your device is already connected to the internet, yo…
  5. Oct 8, 2026INDIA'S BIGGEST SHOPPING SALE IS LIVE TOMORROW IS IT REALLY A DEAL🤡? THIS APP BUYHATKE TE…
  6. Oct 3, 2026𝗧𝗵𝗼𝘀𝗲 𝘄𝗵𝗼 𝘄𝗮𝗻𝘁 𝗿𝗲𝗳𝗲𝗿𝗿𝗮𝗹𝘀 𝗮𝗻𝗱 𝗝𝗼𝗯𝘀 𝗮𝗻𝗱 𝗜𝗻𝘁𝗲𝗿𝗻𝘀𝗵𝗶𝗽�…
Threads Profile ViewerView any public Threads profile without an account.Open ThreadLook →Writing with AI? Make it sound human.Metric37 rewrites AI drafts so they read naturally. Free AI detector, 1,500 words free.Try Metric37 →