每一次求得的最大值是a【0,n】=max(a[1,n]+a[0]*count ,a[0,n-1]+a[n]*count);
所以得到如下:
1 import java.io.*; 2 import java.util.*; 3 public class Main 4 { 5 static int [][] maxValue; 6 private static int getMax(int []value,int left, int right,int count) 7 { 8 if (left <= right) 9 { 10 if (maxValue[left][right] != -1) 11 { 12 return maxValue[left][right]; 13 } 14 int a = getMax(value, left + 1, right, count + 1) + count*value[left]; 15 int b = getMax(value, left, right - 1, count + 1) + count*value[right]; 16 if (a > b) { 17 maxValue[left][right] = a; 18 return a; 19 } else { 20 maxValue[left][right] = b; 21 return b; 22 } 23 } 24 return 0; 25 } 26 public static void main(String args[]) 27 { 28 Scanner cin = new Scanner(System.in); 29 int n = cin.nextInt(); 30 int []value = new int[n]; 31 for (int i = 0;i < n;i++) 32 { 33 value[i] = cin.nextInt(); 34 } 35 int left = 0; 36 int right = n - 1; 37 maxValue = new int[n][n]; 38 for (int i = 0 ;i < n; i++) 39 { 40 for (int j = 0; j < n; j++) 41 { 42 maxValue[i][j] = -1; 43 } 44 } 45 int sum = 0; 46 sum = getMax(value, 0, n - 1, 1); 47 System.out.println(sum); 48 } 49 }