solved 3b
This commit is contained in:
39
src/Problem3b.java
Normal file
39
src/Problem3b.java
Normal file
@@ -0,0 +1,39 @@
|
||||
package src;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.FileReader;
|
||||
import java.io.IOException;
|
||||
|
||||
public class Problem3b {
|
||||
|
||||
public static void main(String[] args) {
|
||||
String filePath = "inputs/inputProblem3.txt";
|
||||
try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
|
||||
String line;
|
||||
long total = 0;
|
||||
while ((line = reader.readLine()) != null) {
|
||||
String maxDigits = maxKDigitsString(line, 12);
|
||||
total += Long.parseLong(maxDigits);
|
||||
}
|
||||
System.out.println("Total maximum joltage: " + total);
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
public static String maxKDigitsString(String digits, int k) {
|
||||
int n = digits.length();
|
||||
char[] stack = new char[k];
|
||||
int top = 0;
|
||||
for (int i = 0; i < n; i++) {
|
||||
char c = digits.charAt(i);
|
||||
while (top > 0 && stack[top - 1] < c && (top - 1 + (n - i)) >= k) {
|
||||
top--;
|
||||
}
|
||||
if (top < k) {
|
||||
stack[top++] = c;
|
||||
}
|
||||
}
|
||||
return new String(stack, 0, k);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user