TGViewer
Data Science Data Science @datascience_official · 566 subscribers
Post #244 67
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 @datascience_official
  1. Oct 8, 2026INDIA'S BIGGEST SHOPPING SALE IS LIVE TOMORROW IS IT REALLY A DEAL🤡? THIS APP BUYHATKE TE…
  2. Oct 3, 2026𝗧𝗵𝗼𝘀𝗲 𝘄𝗵𝗼 𝘄𝗮𝗻𝘁 𝗿𝗲𝗳𝗲𝗿𝗿𝗮𝗹𝘀 𝗮𝗻𝗱 𝗝𝗼𝗯𝘀 𝗮𝗻𝗱 𝗜𝗻𝘁𝗲𝗿𝗻𝘀𝗵𝗶𝗽�…
  3. Sep 30, 2026❤️ Here is the list of highly recommended Telegram channels for your free learning ❤️ Get…
  4. Sep 27, 2026🚨 Earn Passive Money Easily 🚨 Since your device is already connected to the internet, yo…
  5. Sep 26, 2026Hackathon National Research & Innovation Challenge Season 3 📌APPLY LINK : https://bit.ly/…
  6. Sep 13, 2026A-Z of essential data science concepts A: Algorithm - A set of rules or instructions for s…
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 →