Skip to content

Instantly share code, notes, and snippets.

@klepto
Created September 21, 2014 09:21
Show Gist options
  • Select an option

  • Save klepto/a6cf886a494709c9b36f to your computer and use it in GitHub Desktop.

Select an option

Save klepto/a6cf886a494709c9b36f to your computer and use it in GitHub Desktop.
package test;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.LinkedList;
import java.util.Scanner;
public class PathSum {
public static void main(String[] args) throws Exception {
LinkedList<int[]> tiles = loadTiles(new File("tiles.txt"));
System.out.println(calculatePathSum(tiles));
}
private static LinkedList<int[]> loadTiles(File tilesFile)
throws FileNotFoundException {
LinkedList<int[]> tiles = new LinkedList<int[]>();
Scanner in = new Scanner(tilesFile);
while (in.hasNextLine()) {
String[] numberStrings = in.nextLine().split(" ");
int[] numbers = new int[numberStrings.length];
for (int i = 0; i < numberStrings.length; i++) {
numbers[i] = Integer.parseInt(numberStrings[i]);
}
tiles.addFirst(numbers);
}
in.close();
return tiles;
}
private static int calculatePathSum(LinkedList<int[]> tiles) {
while (tiles.size() > 1) {
int[] currentRow = tiles.poll();
int[] parentRow = tiles.poll();
for (int i = 0; i < currentRow.length - 1; i++) {
int max = Math.max(currentRow[i], currentRow[i + 1]);
parentRow[i] += max;
}
tiles.addFirst(parentRow);
}
return tiles.poll()[0];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment