目录
leetcode 121.买卖股票的最佳时机 I(一笔一次买卖)
leetcode 122.买卖股票的最佳时机 II(一笔多次买卖)
leetcode 123.买卖股票的最佳时机 III (两笔多次买卖)
leetcode 188.买卖股票的最佳时机 IV (K笔多次买卖)
leetcode 121.买卖股票的最佳时机 I(一笔一次买卖)
题目:给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。如果你最多只允许完成一笔交易(即买入和卖出一支股票一次),设计一个算法来计算你所能获取的最大利润。(注意:你不能在买入股票前卖出股票)
输入: [7,1,5,3,6,4]
输出: 5
解法:设置两变量 Buy(购买股票之后所剩余的钱) 和 Sell(售卖股票之后所拥有的钱);遍历 prices 数组,Sell 保存 Buy 购买股票(每次只保存 prices 数组的最小值)之后的天数中,prices[i] + Buy 的最大值,也就是 Sell 售卖股票的最大利润。
public int maxProfit(int[] prices) {
if(prices.length == 0) return 0;
int Buy = Integer.MIN_VALUE, Sell = 0;
for(int p : prices) {
Buy = Math.max(Buy, -p);
Sell = Math.max(Sell, Buy + p);
}
return Sell;
}
leetcode 122.买卖股票的最佳时机 II(一笔多次买卖)
题目:给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。设计一个算法来计算你所能获取的最大利润。你可以尽可能地完成更多的交易(多次买卖一支股票)。注意:你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。
输入: [7,1,5,3,6,4]
输出: 7
解法:设置两变量 Buy(购买股票之后所剩余的钱) 和 Sell(售卖股票之后所拥有的钱);遍历 prices 数组,Buy 购买股票(每次保存 Math.max(buy, sell - p) 的值,即剩余最多的钱),Sell 保存 Buy 购买股后 prices[i] + Buy 的最大值,也就是 Sell 售卖股票的最大利润。
public int maxProfit(int[] prices) {
if(prices.length == 0) return 0;
int buy = Integer.MIN_VALUE, sell = 0;
for(int p : prices){
buy = Math.max(buy, sell - p);
sell = Math.max(sell, buy + p);
}
return sell;
}
leetcode 123.买卖股票的最佳时机 III (两笔多次买卖)
题目:给定一个数组,它的第 i 个元素是一支给定的股票在第 i 天的价格。设计一个算法来计算你所能获取的最大利润。你最多可以完成 两笔 交易。注意: 你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。
输入: [7,1,5,3,6,4]
输出: 7
解法:和 leetcode 122.买卖股票的最佳时机 II 解法相同,只是多了一笔交易 。
public int maxProfit(int[] prices) {
int fstBuy = Integer.MIN_VALUE, fstSell = 0;
int secBuy = Integer.MIN_VALUE, secSell = 0;
for(int p : prices) {
fstBuy = Math.max(fstBuy, -p);
fstSell = Math.max(fstSell, fstBuy + p);
secBuy = Math.max(secBuy, fstSell - p);
secSell = Math.max(secSell, secBuy + p);
}
return secSell;
}
leetcode 188.买卖股票的最佳时机 IV (K笔多次买卖)
解法:和 leetcode 123.买卖股票的最佳时机 III 解法相同,只是 K 笔多次买卖 。(注意:当 k >= prices.length/2 为一笔多次买卖)
public int maxProfit(int k, int[] prices) {
if(k == 0) return 0;
if(k >= prices.length/2){
int Buy = Integer.MIN_VALUE, Sell = 0;
for(int p : prices) {
Buy = Math.max(Buy, Sell-p);
Sell = Math.max(Sell, Buy + p);
}
return Sell;
}
else{
int[][] buy = new int[k][2];
for(int i=0; i<k; i++)
buy[i][0] = Integer.MIN_VALUE;
for(int p : prices) {
buy[0][0] = Math.max(buy[0][0], -p);
buy[0][1] = Math.max(buy[0][1], buy[0][0] + p);
for(int i=1; i<k; i++){
buy[i][0] = Math.max(buy[i][0], buy[i-1][1] - p);
buy[i][1] = Math.max(buy[i][1], buy[i][0] + p);
}
}
return buy[k-1][1];
}
}
leetcode 714.买卖股票的最佳时机含手续费
题目:给定一个整数数组 prices,其中第 i 个元素代表了第 i 天的股票价格 ;非负整数 fee 代表了交易股票的手续费用。你可以无限次地完成交易,但是你每次交易都需要付手续费。如果你已经购买了一个股票,在卖出它之前你就不能再继续购买股票了。返回获得利润的最大值。
public int maxProfit(int[] prices, int fee) {
if(prices.length == 0) return 0;
int cash = 0, hold = -prices[0];
for(int i=1; i<prices.length; i++){
cash = Math.max(cash, hold + prices[i] - fee);
hold = Math.max(hold, cash - prices[i]);
}
return cash;
}