# 785. 最大权值和路径

给出 [[1,2,3,4],[3,5,6,7],[9,10,1,2],[4,4,5,5]] ，返回45

解释：从右上角出发，沿着[4,7,6,5,10,9,4]走到左下角。权值和为45。




public class Solution {
public static void main(String[] args) {
int[][] nums = { { 22, 17, 16, 6, 15 }, { 22, 9, 14, 9, 7 },
{ 4, 10, 6, 18, 8 }, { 22, 25, 13, 3, 1 }, { 16, 24, 21, 3, 2 } };
System.out.println(maxWeight(nums));
}

/**
* 求最大权值
*/
public static int maxWeight(int[][] nums) {
int i = 0;
int j = nums[0].length - 1;
int sum = nums[i][j];
while (i != nums.length - 1 || j != 0) {
System.out.println("i:" + i + "j:" + j);
if (j == 0) {
sum = sum + nums[i + 1][j];
i++;
continue;
}
if (i == nums.length - 1) {
sum = sum + nums[i][j - 1];
j--;
continue;
}
if (nums[i][j - 1] > nums[i + 1][j]) {
sum = sum + nums[i][j - 1];
j--;
continue;
} else {
sum = sum + nums[i + 1][j];
i++;
continue;
}
}
return sum;
}
}

public class Solution {
public static void main(String[] args) {
String str = "[[30,30,4,97,48,84,12,44,41,50],[92,80,50,35,5,1,24,60,84,76],[24,82,94,18,64,36,36,17,44,5],[0,5,80,80,60,55,20,60,81,92],[8,18,0,86,48,91,22,8,44,67],[20,84,52,49,74,16,90,15,83,9],[11,2,42,58,76,78,68,11,54,76],[64,36,10,60,6,90,14,40,0,92],[34,60,52,49,63,28,68,40,80,64],[0,25,56,50,21,12,80,75,38,68]]";
int[][] nums = change(str);
System.out.println(maxWeight(nums));
}

/**
* 求最大权值
*/
public static int maxWeight(int[][] nums) {
int i = 0;
int j = nums[0].length - 1;
int sum = nums[i][j];
while (i != nums.length - 1 || j != 0) {
System.out.println("i:" + i + "j:" + j);
if (j == 0) {
sum = sum + nums[i + 1][j];
i++;
continue;
}
if (i == nums.length - 1) {
sum = sum + nums[i][j - 1];
j--;
continue;
}
if (nums[i][j - 1] > nums[i + 1][j]) {
sum = sum + nums[i][j - 1];
j--;
continue;
} else {
sum = sum + nums[i + 1][j];
i++;
continue;
}
}
return sum;
}

/**
* 把字符串转成int[][]
*/
private static int[][] change(String str) {
String[] s = str.split("[,\\]\\[]");
int k = 0;
String[][] arr = new String[10][10];
int[][] in = new int[10][10];
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10;) {
if (!s[k].equals("")) {
arr[i][j] = s[k];
j++;
}
k++;
}
}
for (int i = 0; i < in.length; i++) {
for (int j = 0; j < in.length; j++) {
in[i][j] = Integer.parseInt(arr[i][j]);
}
}
return in;
}
}

• 广告
• 抄袭
• 版权
• 政治
• 色情
• 无意义
• 其他

120