动态规划1: #include <iostream> using namespace std; int N; int data[401]; int sum[401][401]; int maxSum(int m, int n) { if (m <= n) { if(sum[m][n] != 0) { return sum[m][n]; } else { return data[m] + maxSum(m+1, n); } } else { return 0; } } void getMax() { int max = 0; for (int i = 1; i <= N; i++) { for(int j = i; j <= N; j++) { sum[i][j] = maxSum(i, j); if (sum[i][j] > max) { max = sum[i][j]; } } } cout << max << endl; } int main() { cin >> N; for(int i = 1; i <= N; i++) { cin >> data[i]; } getMax(); } 动态规划2: #include <iostream> using namespace std; int N; int data[401]; int MaxSubArray(int n, int* a) { int max = 0; int b = 0; for (int i = 0; i < n; i++) { if (b > 0) b += a[i]; else b = a[i]; if (b > max) max = b; } return max; } int main() { cin >> N; for(int i = 1; i <= N; i++) { cin >> data[i]; } cout << MaxSubArray(N, &data[1]); } 测试数据: >> cat input 400 -86 90 -43 -127 42 97 101 -19 85 87 78 18 -96 -50 84 114 118 65 -50 59 14 -23 25 26 -85 5 44 89 91 18 70 99 -106 -89 -8 35 40 -78 -92 17 76 -66 -55 -44 46 37 14 84 -124 -9 -80 17 35 -120 -90 -18 96 114 -98 -99 -61 -92 63 -35 -89 -21 -87 65 -113 21 69 -72 13 102 -7 -27 -121 -26 16 -79 2 -4 -43 77 -121 -37 89 -1 54 -69 67 62 -1 -54 -90 -89 -9 -45 52 -86 -44 -12 12 31 77 53 100 -71 46 9 -106 118 47 -55 -107 -48 -100 -54 -30 -115 109 -87 34 9 -22 -110 28 -53 -96 -75 -27 23 64 97 89 53 -20 64 -120 -40 80 -90 -124 6 68 32 82 -119 94 -39 45 69 -121 -97 36 41 23 -36 -115 28 33 -18 -3 -90 -79 106 -32 -86 -25 -27 -86 -41 -3 -107 -31 -106 -29 72 41 107 -96 107 -74 122 41 61 23 -89 0 90 101 16 21 106 -70 44 -67 -10 -64 -113 -68 -11 58 74 -27 122 -108 -71 -79 -74 97 -119 -33 -18 112 75 68 108 -34 -34 -104 -40 -63 -124 71 73 81 -9 -47 -81 -79 -96 -38 -79 -118 30 95 -5 -89 -85 -89 52 63 30 81 64 -62 11 29 -116 75 7 -105 -72 -49 19 -15 9 -2 56 -8 15 -33 39 4 121 -55 24 -106 72 -70 99 15 12 -52 85 -27 -117 -124 -8 -16 61 24 -88 -122 46 -125 -42 55 -92 -39 49 -10 -120 -45 55 42 27 94 62 99 -48 -9 65 48 -72 57 -78 64 -115 18 -67 91 -124 12 46 -98 119 60 -98 -78 60 -11 72 66 68 -80 39 -91 -22 111 -95 78 107 -13 74 -61 44 -91 -114 -64 -22 58 -74 35 -69 -45 68 -64 -121 -56 -69 19 105 104 17 69 95 2 34 -92 73 46 89 -83 32 -85 62 -124 -103 27 -117 118 22 59 -64 97 -105 41 -109 -90 28 81 14 75 -2 100 37 -63 -53 -43 -3 -5 32 -44 -57 110 -80 -109 50 result: 1106