βSequence Formation (Contest)
Sequence Formation (Contest) easy Time Limit: 2 sec Memory Limit: 128000 kB
Problem Statement :
You are given an array A of size N. You have to divide this array A into two sequences B and C such that each element of array A is present in either sequence B or C exactly one. Find the maximum possible value of sum(B) - sum(C), where sum(B) represents the sum of elements in sequence B. Input The first line contains a single integer N. The second line contains N space separated integers.
Constraints: 1 β€ N β€ 105 -109 β€ Ai β€ 109 Output Print the maximum possible value of sum(B) - sum(C). Example Sample Input: 4 3 -2 0 1
Sample Output: 6
Explaination: B: {3, 1} C: {0, -2} Sum(B) = 4, Sum(C) = -2 Sum(B) - Sum(C) = 4 - (-2) = 4 + 2 = 6
link:https://my.newtonschool.co/playground/code/bz65yj7ohkyb/
```java
import java.io.*; // for handling input/output
import java.util.*; // contains Collections framework
// don't change the name of this class
// you can add inner classes if needed
class Main {
public static void main (String[] args) {
// Your code here
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] arr = new int[n];
for(int i = 0; i < n; i++){
arr[i] = sc.nextInt();
}
Arrays.sort(arr);
int sumB = 0;
int sumC = 0;
for(int x = arr.length - 1; x >= 0; x--){
if(sumB > sumC){
sumC += arr[x];
} else{
sumB += arr[x];
}
}
System.out.print(sumB-sumC);
}
}
```
Last updated