Popular Posts

Wednesday, March 23, 2011

Max Downward sum

package arrays;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
* Input: 2
* 3
* 1
* 2 1
* 1 2 3
*
* 4
* 1
* 1 2
* 4 1 2
* 2 3 1 1
*
* Output: 5
* 9
*
* @author rajeevprasanna
*
*/
public class MaxDownwardSum {
public static void main(String[] args) throws NumberFormatException,
IOException {

BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(in.readLine());
int n, i, j;

int[][] a = new int[100][100];

while (t-- > 0) {
n = Integer.parseInt(in.readLine());
for (i = 0; i < n; i++) {
for (j = 0; j <= i; j++) {
a[i][j] = Integer.parseInt(in.readLine());
}
}
for (i = n - 2; i >= 0; i--) {
for (j = 0; j <= i; j++) {
a[i][j] += max(a[i + 1][j], a[i + 1][j + 1]);
}
}
System.out.println(a[0][0]);
}
}

private static int max(int a, int b) {
return a > b ? a : b;
}
}

No comments:

Post a Comment