返回列表 發帖

最大連續子序列和

本帖最後由 tonyh 於 2023-2-10 19:51 編輯

試使用動態規劃法(DP),求最大連續子序列和。
               
index              0   1    2   3   4   5   6   7   8
data[ ]           -2   1  -3   4  -1   2   1  -5   4
curMaxSum    -2   1  -2   4   3   5   6   1   5
totMaxSum     -2   1   1   4   4   5   6   6   6

範例輸入 1:-2 1 -3 4 -1 2 1 -5 4
範例輸出 1:6


範例輸入 2:0 -2 3 5 -1 2
範例輸出 2:9
  1. import java.io.BufferedReader;
  2. import java.io.InputStreamReader;

  3. public class Ch01 {

  4.         BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
  5.         String raw[];
  6.         int curMaxSum, totMaxSum;
  7.         Ch01() throws Exception
  8.         {
  9.                 raw=br.readLine().split(" ");
  10.                 for(int i=0, len=raw.length; i<len; i++)
  11.                 {
  12.                         int t=Integer.parseInt(raw[i]);
  13.                         if(i==0)
  14.                         {
  15.                                 curMaxSum=t;
  16.                                 totMaxSum=t;
  17.                         }
  18.                         curMaxSum=Math.max(curMaxSum+t, t);
  19.                         totMaxSum=Math.max(curMaxSum, totMaxSum);
  20.                 }
  21.                 System.out.println(totMaxSum);
  22.         }
  23.         public static void main(String[] args) throws Exception{
  24.                 new Ch01();
  25.         }
  26. }
複製代碼
  1. import java.io.BufferedReader;
  2. import java.io.InputStreamReader;

  3. public class Ch01 {

  4.         BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
  5.         String raw[];
  6.         int len, data[];
  7.         Ch01() throws Exception
  8.         {
  9.                 raw=br.readLine().split(" ");
  10.                 len=raw.length;
  11.                 data=new int[len];
  12.                 for(int i=0; i<len; i++)
  13.                         data[i]=Integer.parseInt(raw[i]);
  14.                 System.out.println(maxSubArray(data));
  15.         }

  16.         int maxSubArray(int data[])
  17.         {
  18.                 int curMaxSum=data[0];
  19.                 int totMaxSum=data[0];
  20.                 for(int i=1; i<len; i++)
  21.                 {
  22.                         curMaxSum=Math.max(curMaxSum+data[i],data[i]);
  23.                         totMaxSum=Math.max(totMaxSum, curMaxSum);
  24.                 }
  25.                 return totMaxSum;
  26.         }

  27.         public static void main(String[] args) throws Exception{
  28.                 new Ch01();
  29.         }
  30. }
  31. /*
  32. -2 11 -4 13 -5 -2
  33. 11-4+13=20

  34. -2 1 -3 4 -1 2 1 -5 4
  35. 4-1+2+1=6

  36. 1 -2 3 5 -3 2
  37. 3+5=8

  38. 0 -2 3 5 -1 2
  39. 3+5-1+2=9

  40. -9 -2 -3 -5 -3
  41. -2=-2
  42. */
複製代碼

返回列表