-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathConsecutiveBudget.java
83 lines (66 loc) · 2.64 KB
/
ConsecutiveBudget.java
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
import java.util.HashSet;
public class ConsecutiveBudget {
public static void main(String[] args) {
int seqArray[] = { 2, 3, 10, 1, 1, 2, 1 };
int budget = 7;
System.out.println("m elements: ");
System.out.println(printElementList(seqArray));
int conNum = longestConsecutive(seqArray);
budgetSelection(seqArray, budget, conNum, seqArray.length);
System.out.println("QED");
}
private static String printElementList(int[] seqArray) {
int Len = seqArray.length;
StringBuilder sb = new StringBuilder("[ ");
for (int i = 0; i < Len; i++) {
sb.append(seqArray[i] + ", ");
}
sb.setLength(sb.length() - 2);
sb.append(" ]");
return sb.toString();
}
private static int longestConsecutive(int[] seqArray) {
int longestConsecutiveIndex = 0;
int Len = seqArray.length;
HashSet<Integer> numSet = new HashSet<Integer>();
for (int i = 0; i < Len; i++) {
numSet.add(seqArray[i]);
}
for (int i = 0; i < Len; i++) {
int tempConsecutive = 0;
int val = seqArray[i];
tempConsecutive = checkConsecutive(tempConsecutive, val, numSet);
if (tempConsecutive > longestConsecutiveIndex) {
longestConsecutiveIndex = tempConsecutive;
}
}
return longestConsecutiveIndex;
}
private static int checkConsecutive(int tempConsecutive, int num, HashSet<Integer> numSet) {
if (numSet.contains(num)) {
tempConsecutive++;
numSet.remove(num);
tempConsecutive = checkConsecutive(tempConsecutive, num + 1, numSet);
tempConsecutive = checkConsecutive(tempConsecutive, num - 1, numSet);
}
return tempConsecutive;
}
private static void budgetSelection(int[] seqArray, int budget, int consecutiveIndex, int num) {
int[] budgetSelect = new int[num - consecutiveIndex];
for (int i = consecutiveIndex; i < num; i++) {
budgetSelect[(i - consecutiveIndex)] = (int) (seqArray[i]);
}
int sum = 0;
for (int number : budgetSelect) {
sum += number;
}
System.out.println("output elements: ");
System.out.println(printElementList(budgetSelect));
System.out.println("The budget Selection length is " + budgetSelect.length + ". and sum is " + sum + ".");
if (sum < budget) {
System.out.println("The budget is under by: " + (budget - sum));
} else {
System.out.println("The budget is over by: " + (sum - budget));
}
}
}