Advertisement
CR7CR7

MaximumMinimumSum

May 25th, 2023
1,386
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.76 KB | None | 0 0
  1. class Solution {
  2.     public int sumDiff(int []arr, int M) {
  3.       // code here
  4.       // sort the array in ascending order
  5.       Arrays.sort(arr);
  6.       // initialize the sum variables
  7.       int maxSum = 0;
  8.       int minSum = 0;
  9.       // declare the variable N as the length of the array
  10.       int N = arr.length; // added this line
  11.       // loop through the array from the end to get the maximum sum of N-M elements
  12.       for (int i = N - 1; i >= N-M; i--) { // changed this line
  13.         maxSum += arr[i];
  14.       }
  15.       // loop through the array from the start to get the minimum sum of M elements
  16.       for (int i = 0; i < M; i++) {
  17.         minSum += arr[i];
  18.       }
  19.       // return the difference between the sums
  20.       return maxSum - minSum;
  21.     }
  22. }
  23.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement