Skip to content

Instantly share code, notes, and snippets.

@pcj
Last active November 17, 2016 15:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pcj/ed8020dd5af08b5430c5d852e0c5431b to your computer and use it in GitHub Desktop.
Save pcj/ed8020dd5af08b5430c5d852e0c5431b to your computer and use it in GitHub Desktop.
Dynamic Programming Problem
/**
* SumArray. Given an input list of integers 'A' with length N,
* calculate a NxN matrix 'B' such that the value of a cell B(i,j) is the
* sum of A(i)..A(j) forall i<=j.
*/
public class SumArray {
public static void main(String[] args) {
int[] a = new int[]{ 12, 3, 6, 2, 23, 44 };
int[][] b = makeArray(a);
System.out.println("--- INPUT ---");
printRow(a);
System.out.println("--- OUTPUT ---");
for(int[] row : b) {
printRow(row);
}
}
static int[][] makeArray(int[] a) {
int n = a.length;
int[][] b = new int[n][n];
for (int i = 0; i < n; i++) {
for (int j = i; j < n; j++) {
if (i == 0) {
// If this is the first row, calculate the sum based on the
// current into the input array (a[i]) and the aggregate sum
// calculated so far (the previous cell in this column)
b[i][j] = a[j] + (j > 0 ? b[i][j - 1] : 0);
} else {
// If this is not the first row, we can find the sum based
// on the difference between the cell above us (previous
// column) and the index value of the input array (a[i -
// 1]).
b[i][j] = b[i - 1][j] - a[i - 1];
}
}
}
return b;
}
static void printRow(int[] row) {
for (int i : row) {
System.out.print(i);
System.out.print("\t");
}
System.out.println();
}
}
@pcj
Copy link
Author

pcj commented Nov 17, 2016

--- INPUT ---
12	3	6	2	23	44	
--- OUTPUT ---
12	15	21	23	46	90	
0	3	9	11	34	78	
0	0	6	8	31	75	
0	0	0	2	25	69	
0	0	0	0	23	67	
0	0	0	0	0	44

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment