蘇蘇醬陪你學動態規劃(一)——股票買賣
阿新 • • 發佈:2018-11-08
1、問題描述
給你一串數字,表示每天的股票價格,你在某一天買進,並在未來的某一天賣出,請求出最大的利潤值。
例:
1,2,6,4,3
那麼應該在第一天買進,第三天賣出,最多賺5
2、解題思路
截至某一天,最大的利潤值其實之和它前一天的最大利潤值有關,那麼採用記憶化自低向上的求解方法即可求得最優解。時間複雜度為O(n)。
3、JAVA程式實現
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class best_time_to_buy_and_sell_stock{ public static void main(String[] args) throws IOException{ // TODO Auto-generated method stub /* * price[i]:the price of each day * L[i]:lowest price up to i-th day * P[i]:max profit up to i-th day * P[i] = max(P[i-1],price[i]-L[i-1]) */ BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String line = in.readLine(); String[] s = line.split(" "); int[] price = new int[s.length]; for(int i = 0 ; i<s.length;i++) { price[i] = Integer.parseInt(s[i]); } int[] L = new int[price.length]; int[] P = new int[price.length]; L[0] = price[0]; P[0] = 0; for (int i = 1; i<price.length;i++) { L[i] = Math.min(L[i-1],price[i]); P[i] = Math.max(P[0], price[i]-L[i-1]); } System.out.println(P[P.length-1]); } }