Advertisement
uopspop

Untitled

Dec 20th, 2017
127
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.60 KB | None | 0 0
  1. package prac;
  2.  
  3. import java.util.ArrayList;
  4. import java.util.Arrays;
  5. import java.util.List;
  6.  
  7. /**
  8. 從[0]開始
  9. 每次都有至多六種選擇
  10. 最後抵達[n-1]
  11. 目的: sum是最大的
  12.  
  13. (DP)
  14. 重點一: 用一個陣列紀錄每次六個選項中的最佳結果
  15. 重點二: 概念上是將每次開頭都當成一個新的子集合,之前的資訊即為確認資訊。程式跑的邏輯像是
  16. (1) 從第0個(i)開始,向前移動六次(j)(因為是第一輪,所以沒有前一個最佳結果可參考)
  17. (2) 再來,從第1個(i)開始,向前移動六次(j)。
  18.     每次比較 "上一輪的最佳結果bestResult[j]" vs "這一輪的起始值bestResult[i]+當下這格的值Ary[j]"。
  19.     取較大者
  20. (3) 循環下去
  21. (4) 何時結束: 當i與j都碰到Ary[j]
  22.  * @author sam
  23.  *
  24.  */
  25. public class NumberSolitaire{
  26.     public static int SUBARRAY_MINIMUM_LENGTH = 2;
  27.     public static void main(String a[]){
  28.        
  29.         int [] ary = {1, -2, 0, 9, -1, -2}; // 五個 - ans: 8
  30. //        int [] ary = {1, -2, -3, -4, -1, -7, -9, -10}; // 八個 - ans: -10
  31.         int solution = solution(ary);
  32.         System.out.println("solution: " + solution);
  33.     }    
  34.  
  35.     /**
  36.      * TIME(O): (n-1) + (n-1)/2 + (n-1)/3 + (n-1)/4 + ..... + (n-1)/(n-1) ->  / 1*2*3*....*(n-1)
  37.      * SPACE(O): N
  38.      * @param A
  39.      * @return
  40.      */
  41.     private static int solution(int A[])
  42.     {  
  43.         // N //  N is an integer within the range [2..100,000];
  44.         // A[] // each element of array A is an integer within the range [−10,000..10,000].
  45.         int N = A.length;
  46.         int[] bestResult = new int[N]; // 紀錄目前最佳結果
  47.         Arrays.fill(bestResult, Integer.MIN_VALUE); // 塞入最小值
  48.        
  49.         // 初始值
  50.         bestResult[0] = A[0];
  51.         for (int i = 0;i < A.length;i++) {
  52. //          System.out.printf(" index: %d %n", i);
  53.             // 下六個這狀況把它記起來
  54.             for (int j = i + 1; (j < A.length) && (i < A.length) && j < (i + 1) + 6; j++) {
  55.                 // 比較 之前最高 與 加上A[j] 誰大誰小
  56.                 int preMaxResult = bestResult[j]; // 暫存目前最大可能數
  57.                 int nowMaxResult = bestResult[i] + A[j]; // 前一步驟(i)最大可能數 + 現在數值A[j]
  58.                 bestResult[j] = Math.max(preMaxResult, nowMaxResult);
  59. //              System.out.printf("(i,j)=(%d,%d) 上一個最大結果: %11d or 加上當下的結果: %4d -> 較大結果: %4d ###### %n", i, j, preMaxResult , bestResult[i] + A[j], bestResult[j]);
  60.             }
  61.         }
  62.         // {1, -2, -3, -4, -1, -7, -9, -10}
  63.        
  64.         return bestResult[bestResult.length-1];
  65.     }
  66. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement