Repository navigation
Expand file tree
/
Copy pathSolution.java
More file actions
87 lines (66 loc) · 2.46 KB
/
Copy pathSolution.java
File metadata and controls
87 lines (66 loc) · 2.46 KB
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package com.abn.dsalgos.datastructure.problems;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
/*
Given an array, you must increment any duplicate elements until all its elements are unique.
In addition, the sum of its elements must be the minimum possible within the rules.
For example, if arr = [3, 2, 1, 2, 7], then arrunique = [3, 2, 1, 4, 7] and its elements
sum to a minimal value of 3 + 2 + 1 + 4 + 7 = 17.
Complete the getMinimumUniqueSum function in the editor below to create an array of unique elements with a minimal sum.
Return the integer sum of the resulting array.
getMinimumUniqueSum has the following parameter(s):
arr: an array of integers to process
*/
public class Solution {
public static void main(String[] args)
throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));
int arrCount = Integer.parseInt(bufferedReader.readLine().trim());
List<Integer> arr = new ArrayList<>();
for (int i = 0; i < arrCount; i++) {
int arrItem = Integer.parseInt(bufferedReader.readLine().trim());
arr.add(arrItem);
}
int result = Result.getMinimumUniqueSum(arr);
bufferedWriter.write(String.valueOf(result));
bufferedWriter.newLine();
bufferedReader.close();
bufferedWriter.close();
}
}
class Result {
/*
* Complete the 'getMinimumUniqueSum' function below.
*
* The function is expected to return an INTEGER.
* The function accepts INTEGER_ARRAY arr as parameter.
*/
public static int getMinimumUniqueSum(List<Integer> arr) {
Set<Integer> unique = new HashSet();
for (int i : arr) {
if (!unique.contains(i)) {
unique.add(i);
} else {
while (unique.contains(i)) {
i++;
}
unique.add(i);
}
}
Iterator iterator = unique.iterator();
int sum = 0;
while (iterator.hasNext()) {
sum += (int) iterator.next();
}
return sum;
}
}