从第一行的第一个数字开始,计算下一行临近的两个数字中较大的一个,统计所有临近较大数字的总和,看下例:
5
9 6
4 6 8
0 7 1 5
计算总和为:5+9+6+7=27
用程序计算附件中的总和值。
simplest Demo:
package algorith;
import java.io.InputStream;
import java.util.List;
import org.apache.commons.io.IOUtils;
public class TestTriangle {
/**
* @param args
*/
public static void main(String[] args) throws Exception {
InputStream ins = TestTriangle.class.getResourceAsStream("file2.txt");
List<String> lines = IOUtils.readLines(ins);
for(String line:lines){
//System.out.println(line);
}
int[][] arrays = new int[lines.size()][];
int i = 0;
for(String line:lines){
String[] temp = line.split(" ");
arrays[i] = getIntArray(temp);
i++;
}
int max = getMax(arrays);
System.out.println("Max=="+max);
}
public static int[] getIntArray(String[] strs){
int[] temp = new int[strs.length];
int i = 0;
//StringBuffer sb = new StringBuffer("");
for(String s:strs){
temp[i] = Integer.parseInt(s);
//sb.append(temp[i]).append("-");
i++;
}
//System.out.println("=length="+temp.length);
return temp;
}
public static int getMax(int[][] arrays){
int max = arrays[0][0];
//System.out.println("=number="+arrays[0][0]);
int px=0,py=0;
for(int i=1;i<arrays.length;i++){
px = i;
int pyl = py;
int pyr = py+1;
if(arrays[px][pyl]>=arrays[px][pyr]){
py = pyl;
}else{
py = pyr;
}
//System.out.println("=number="+arrays[px][py]);
max += arrays[px][py];
}
return max;
}
}
运算结果为655321,结果正确吗?