File tree Expand file tree Collapse file tree
3727-maximum-alternating-sum-of-squares Expand file tree Collapse file tree Original file line number Diff line number Diff line change 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+ } ;
You can’t perform that action at this time.
0 commit comments