Skip to content

Commit f090e64

Browse files
committed
Time: 216 ms (100%), Space: 86.9 MB (100%) - LeetHub
1 parent 4caf3e7 commit f090e64

1 file changed

Lines changed: 30 additions & 0 deletions

File tree

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
const maxAlternatingSum = (nums: number[]): number => {
2+
// Key insight: Since we square all values, signs don't matter - use absolute values
3+
const absoluteValues = nums.map(Math.abs);
4+
absoluteValues.sort((a, b) => a - b);
5+
6+
const arrayLength = absoluteValues.length;
7+
let maxScore = 0n;
8+
9+
// Greedy strategy: Pair largest with smallest to maximize (large² - small²)
10+
// Process pairs from both ends moving inward
11+
const pairCount = Math.floor(arrayLength / 2);
12+
13+
for (let pairIndex = 0; pairIndex < pairCount; pairIndex++) {
14+
const largestValue = BigInt(absoluteValues[arrayLength - pairIndex - 1]);
15+
const smallestValue = BigInt(absoluteValues[pairIndex]);
16+
17+
// Add difference: large² - small²
18+
const pairContribution = largestValue * largestValue - smallestValue * smallestValue;
19+
maxScore += pairContribution;
20+
}
21+
22+
// If odd number of elements, add the middle element squared (no pair to subtract)
23+
if (arrayLength % 2 === 1) {
24+
const middleIndex = Math.floor(arrayLength / 2);
25+
const middleValue = BigInt(absoluteValues[middleIndex]);
26+
maxScore += middleValue * middleValue;
27+
}
28+
29+
return Number(maxScore);
30+
};

0 commit comments

Comments
 (0)