1 package com.yyy.five.day; 2 3 4 /** 5 * 动态规划求最大连续字序列 6 * 7 * @author YYY 8 * 9 */ 10 public class Opp1 { 11 12 13 public static void main(String[] args) { 14 int a[] = { -2, 11, -4, 13, -5, 2, -5, -3, 12, -9 }; 15 System.out.println(getMaxSquence1(a)); 16 System.out.println(getMaxSquence2(a)); 17 } 18 19 20 public static int getMaxSquence1(int a[]) { 21 int max = a[0]; 22 int v = 0; 23 for (int i = 0; i < a.length; i++) { 24 v = 0; 25 for (int j = i; j < a.length; j++) { 26 v += a[j]; 27 if (v > max) { 28 max = v; 29 } 30 } 31 } 32 return max; 33 } 34 35 36 public static int getMaxSquence2(int a[]) { 37 int max = a[0]; 38 int v = 0; 39 for (int i = 0; i < a.length; i++) { 40 v += a[i]; 41 if (v > max) { 42 max = v; 43 } else if (v < 0) { 44 v = 0; 45 } 46 } 47 return max; 48 } 49 }