这次带来的是Best time to buy and sell stock大合集,在leetcode上这一合集共有6道题,难度从easy到hard不等,我们这次记录下这一合集的全部解法并记录下解题的思考想法。所有的题目都是计算不同计算规则下股票的最大利润。
一,Best Time to Buy and Sell Stock (一次交易)
Say you have an array for which the ith element is the price of a given stock on day i.
If you were only permitted to complete at most one transaction (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit.
Note that you cannot sell a stock before you buy one.
本题意思就是你得到一系列在接下来几天的股票价格,现在你被允许只用一次交易(就是买进再卖出)来获取最大利益。 这个很简单,只要用双指针的方法记住获利的大小,再筛选出最大的即可。
我的解法:
class Solution {
public int maxProfit(int[] prices) {
int profit = 0;
for(int i = 0; i < prices.length-1;i++) {
for(int j = i+1; j < prices.length;j++) {
profit = Math.max(profit, prices[j]-prices[i]);
}
}
return profit;
}
}
二,Best Time to Buy and Sell Stock Ⅱ(多次交易)
Say you have an array for which the ith 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 (i.e., buy one and sell one share of the stock multiple times).
Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again).
意思是买卖股票时可以不计买卖次数,但是必须在买之前先把以前的股票卖掉。然后求能获利最大的额度。 这样的话也很简单,只要遇见下一天的价格比这一天价格高的话,就卖出,这样最后的利润肯定是最高的。(市场放开,有利就图啊)
class Solution {
public int maxProfit(int[] prices) {
int profit = 0;
for(int i = 1; i < prices.length; i++){
if(prices[i-1] < prices[i])
profit += prices[i]-prices[i-1];
}
return profit;
}
}
三,Best Time to Buy and Sell Stock III(最多买卖两次)
Say you have an array for which the ith element is the price of a given stock on day i.
Design an algor