一个简单的动态规划问题
设一个dataArray二维数组,dataArray[x][y]表示,从x到y个数的和。
则dataArray[x][x]存的是一开始一位数组array[x]的值。
又比如dataArray[1][2] = array[1]+array[2];
例如:
1 package com.example.test; 2 3 public class Solution { 4 public int FindGreatestSumOfSubArray(int[] array) { 5 int [][]dataArray= new int[array.length][array.length]; 6 for (int i = 0; i < array.length;i++) { 7 dataArray[i][i] = array[i]; 8 } 9 10 int max = Integer.MIN_VALUE; 11 for (int i = 0 ;i < array.length; i++) { 12 if (array[i] > max) { 13 max = array[i]; 14 } 15 } 16 for (int step = 1;step < array.length; step++) { 17 for (int i = 0; i < array.length; i++) { 18 if (i+step < array.length) { 19 dataArray[i][i+step] = dataArray[i + 1][i+step] + dataArray[i][i]; 20 if (dataArray[i][i + step] > max) { 21 max = dataArray[i][i + step]; 22 } 23 } 24 } 25 } 26 27 /* 28 for (int i = 0; i < array.length; i++) { 29 for (int j = 0; j < array.length; j++) { 30 System.out.print(dataArray[i][j] + " "); 31 } 32 System.out.println(); 33 }*/ 34 return max; 35 } 36 public static void main(String []args) { 37 int []array = {1,-2,3,10,-4,7,2,-5}; 38 int max = new Solution().FindGreatestSumOfSubArray(array); 39 System.out.println(max); 40 } 41 }