-
Notifications
You must be signed in to change notification settings - Fork 21.1k
Expand file tree
/
Copy pathMaxAlternatingSum.java
More file actions
43 lines (34 loc) · 965 Bytes
/
MaxAlternatingSum.java
File metadata and controls
43 lines (34 loc) · 965 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package com.thealgorithms.devutils;
import java.util.Arrays;
/**
* Computes the maximum alternating sum based on the squared values of the input array.
*
* Steps:
* 1. Convert nums[i] to nums[i]^2
* 2. Sort the squared array
* 3. Select the largest (n + 1) / 2 elements
* 4. Use formula: result = 2 * sum(selected) - totalSum
*
* Time Complexity: O(n log n)
* Space Complexity: O(n)
*/
public class MaxAlternatingSum {
public long maxAlternatingSum(int[] nums) {
int n = nums.length;
long[] squared = new long[n];
for (int i = 0; i < n; i++) {
squared[i] = (long) nums[i] * nums[i];
}
Arrays.sort(squared);
int k = (n + 1) / 2;
long total = 0;
for (long v : squared) {
total += v;
}
long maxHalf = 0;
for (int i = n - 1; i >= n - k; i--) {
maxHalf += squared[i];
}
return 2 * maxHalf - total;
}
}