Skip to content

Commit 8d16b8e

Browse files
committed
07/28 arrayPairSum
1 parent bbd6492 commit 8d16b8e

1 file changed

Lines changed: 13 additions & 8 deletions

File tree

java/arrayPairSum.java

Lines changed: 13 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,25 @@
1+
/*
2+
We need to form the pairings of the array's elements such that the overall sum of the minimum out of such pairings is maximum. Thus, we can look at the operation of choosing the minimum out of the pairing, say (a, b)(a,b) as incurring a loss of a - ba−b(if a> ba>b), in the maximum sum possible.
3+
4+
The total sum will now be maximum if the overall loss incurred from such pairings is minimized. This minimization of loss in every pairing is possible only if the numbers chosen for the pairings lie closer to each other than to the other elements of the array.
5+
6+
Taking this into consideration, we can sort the elements of the given array and form the pairings of the elements directly in the sorted order. This will lead to the pairings of elements with minimum difference between them leading to the maximization of the required sum.
7+
8+
O(nlon n)
9+
O(1)
10+
*/
11+
12+
113
public class Solution {
214
public int arrayPairSum(int[] nums) {
3-
4-
if(nums.length == 0)
5-
return 0;
6-
15+
if(nums.length == 0) return 0;
716
Arrays.sort(nums);
8-
917
int sum = 0;
10-
1118
for(int i=0; i<nums.length; i++)
1219
{
1320
sum += nums[i];
1421
i++;
1522
}
16-
1723
return sum;
18-
1924
}
2025
}

0 commit comments

Comments
 (0)