Given an array A, you can rearrange the elements o...
बनाया गया: 3 सितंबर 2025
का उपयोग करके उत्तर दिया गया GPT-5 Thinking द्वारा Chat01
बनाया गया: 3 सितंबर 2025
का उपयोग करके उत्तर दिया गया GPT-5 Thinking द्वारा Chat01
Given an array A, you can rearrange the elements of A and let array of prefix sum of A be ‘pref’, maximize summation(((-1)^i)* pref) and return this max value.
code in java
pythonimport itertools, random def max_value(arr): n=len(arr) best=-10**18 for perm in itertools.permutations(arr): pref=0 total=0 for i,x in enumerate(perm): pref+=x total+= ((-1)**i)*pref best=max(best,total) return best def formula(arr): arr=sorted(arr) n=len(arr) if n%2==1: m=(n+1)//2 return sum(arr[-m:]) else: m=n//2 return -sum(arr[:m]) for n in range(1,6): for _ in range(50): arr=[random.randint(-5,5) for __ in range(n)] if max_value(arr)!=formula(arr): print("Mismatch", n, arr, max_value(arr), formula(arr)) raise SystemExit print("All ok")
Here’s a clean, optimal solution in Java.
Idea (0-based i):
If we define pref[i] = A[0] + … + A[i] and maximize
S = Σ_{i=0..n-1} (-1)^i * pref[i], then only elements placed at indices with the same parity as n-1 affect S.
n is odd, the contributing indices are even with + sign ⇒ put the largest ⌈n/2⌉ elements there ⇒ S = sum(largest ⌈n/2⌉).n is even, the contributing indices are odd with − sign ⇒ put the smallest n/2 elements there ⇒ S = − sum(smallest n/2).So we only need to sort once.
javaimport java.util.Arrays; public class MaxAltPrefSum { /** * Returns max over all permutations of A of: * S = sum_{i=0..n-1} (-1)^i * pref[i], * where pref[i] = sum_{k=0..i} A[k]. * * Time: O(n log n) due to sort * Space: O(1) extra (sorting in place) */ public static long maxAlternatingPrefSum(int[] A) { int n = A.length; Arrays.sort(A); // ascending long ans = 0L; if ((n & 1) == 1) { // n is odd: take sum of largest ceil(n/2) elements int m = (n + 1) / 2; for (int i = n - 1; i >= n - m; --i) { ans += A[i]; } } else { // n is even: negative of sum of smallest n/2 elements int m = n / 2; for (int i = 0; i < m; ++i) { ans -= A[i]; } } return ans; } // quick demo public static void main(String[] args) { System.out.println(maxAlternatingPrefSum(new int[]{3, 1, 2})); // 5 (place 3,1,2 → pref: 3,4,6 → +3 -4 +6 = 5) System.out.println(maxAlternatingPrefSum(new int[]{-5, -2, 4, 7})); // 7 (n even → -(sum of two smallest: -5 + -2) = 7) System.out.println(maxAlternatingPrefSum(new int[]{5})); // 5 } }
📝 If your definition uses 1-based i (i.e., i = 1..n and (-1)^1 = -1 for the first prefix), just swap the branches:
n even → sum of largest n/2 elements;n odd → negative sum of smallest ⌈n/2⌉ elements.