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]);
}
}