題目描述 I
Say you have an array for which the i th element is the price of a given stock on day i.
If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.
- 思路
貪心算法,初始化一個最小值,依次遍歷。
若大于當(dāng)前值則更新最小值;否則更新最大收益。
public class Solution {
public int maxProfit(int[] prices) {
if(prices == null || prices.length < 2)
return 0;
int ans = 0;
int minV = prices[0];
for(int i=1; i<prices.length; i++){
if(minV > prices[i]){
minV = prices[i];
}else{
ans = Math.max(ans, prices[i]-minV);
}
}
return ans;
}
}
題目描述 II
Say you have an array for which the i th element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
- 思路
求若干天最大收益(首先要買到股票才能賣出獲得利潤),因此當(dāng)只有一天時利潤為0;其他情況是在一個遞增區(qū)間內(nèi),最低價買入最高價賣出。
而在一個遞增區(qū)間內(nèi),只要上一天比下一天價格低,就可以獲得這兩天的差價。順序遍歷求總和即可
public class Solution {
public int maxProfit(int[] prices) {
if(prices == null || prices.length < 2)
return 0;
int ans = 0;
for(int i=1; i<prices.length; i++){
if(prices[i-1] < prices[i]){
ans += (prices[i] - prices[i-1]);
}
}
return ans;
}
}
題目描述III
Say you have an array for which the i th element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete at most two transactions.
Note:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
- 思路
求最多兩次交易的最大利潤。
假如只進(jìn)行1次交易的話會更簡單一些:用sell1表示初始時身上的凈利潤為0,buy1用于存放最便宜股價的價格。一個循環(huán)表示時間一天天推移,第一天時buy1記錄下第一天買入股票的最低花費,之后每進(jìn)入新的一天(今天),就用buy1表示前些天最便宜的股價,sell1保存了前些天買入最便宜股票之后再在賣出股票的最大利潤。新的一天到來,再用buy1繼續(xù)記錄最低股價,再計算出在今天拋售那個最低價股票后的利潤,如果這個利潤比之前保存的sell1高,那就更新sell1,否則,sell1不變。如此循環(huán)下去,到最后一天結(jié)束,sell1就記錄了一次交易的最大利潤。
進(jìn)行多次交易的道理是可以類推的。
參考鏈接
public class Solution {
public int maxProfit(int[] prices) {
if(prices == null || prices.length <= 1)
return 0;
int buy1 = Integer.MIN_VALUE;
int sell1 = 0;
int buy2 = Integer.MIN_VALUE;
int sell2 = 0;
for(int i=0; i<prices.length; i++){
//第一次買的最低花費(負(fù)收入求最大)
buy1 = Math.max(buy1, -prices[i]);
//第一次賣出的最大收益
sell1 = Math.max(sell1, prices[i] + buy1);
//用第一次賺的利潤求得第二次買入時剩余的最大利潤
buy2 = Math.max(buy2, sell1 - prices[i]);
//兩次交易最大利潤
sell2 = Math.max(sell2, prices[i] + buy2);
}
return sell2;
}
}