参考代码:
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); int[][] arr =new int[n + 1][n + 1]; for(int i = 1; i <= n; i++) for(int j = 1; j <= i; j++) arr[i][j] = scanner.nextInt(); scanner.close(); int[][] dp = new int[n + 1][n + 1]; dp[1][1] = arr[1][1]; for(int i = 2; i <= n; i++) for(int j = 1; j <= i; j++) dp[i][j] = Math.max(dp[i - 1][j], dp[i - 1][j - 1]) + arr[i][j]; int res = 0; for(int i = 1; i <= n; i++) res = Math.max(res, dp[n][i]); System.out.print(res); } }
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); int[][] arr =new int[n + 1][n + 1]; for(int i = 1; i <= n; i++) for(int j = 1; j <= i; j++) arr[i][j] = scanner.nextInt(); scanner.close(); int[] dp = new int[n + 1]; dp[1] = arr[1][1]; int res = 0; for(int i = 2; i <= n; i++) for(int j = i; j > 0; j--) { dp[j] = Math.max(dp[j], dp[j - 1]) + arr[i][j]; res = Math.max(res, dp[j]); } System.out.print(res); } }
0.0分
5 人评分