Leetcode 121. Best Time to Buy and Sell Stock I
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.
Example 1:
Input: [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
Not 7-1 = 6, as selling price needs to be larger than buying price.
Example 2:
Input: [7,6,4,3,1]
Output: 0
Explanation: In this case, no transaction is done, i.e. max profit = 0.
解题思路一:用一个变量记录遍历过数中的最小值,然后每次计算当前值和这个最小值之间的差值最为利润,然后每次选较大的利润来更新。当遍历完成后当前利润即为所求,代码如下:
class Solution {
public:
int maxProfit(vector<int>& prices)
{
if(prices.size() <= 1)
return 0;
int res = 0;
int buy = INT_MAX;
for(int i = 0; i < prices.size(); i++)
{
buy = min(buy, prices[i]);
res = max(res, prices[i] - buy);
}
return res;
}
};
解题思路二:
动态规划思想,维护两个变量,一个是到目前为止最好的交易,另一个是在当天卖出的最佳交易(也就是局部最优)。其实,就是求一个数组中连续子数组差最大。
状态转移方程:local = Math.max(local+prices[i+1]-prices[i],0)
代码:
public int maxProfit(int[] prices) {
if(prices==null || prices.length==0)
return 0;
int local = 0;
int global = 0;
for(int i=0;i<prices.length-1;i++)
{
local = Math.max(local+prices[i+1]-prices[i],0);
global = Math.max(local, global);
}
return global;
}
[LeetCode] Best Time to Buy and Sell Stock 买卖股票的最佳时间
122. Best Time to Buy and Sell Stock II
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).
Example 1:
Input: [7,1,5,3,6,4]
Output: 7
Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4.
Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3.
Example 2:
Input: [1,2,3,4,5]
Output: 4
Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.
Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are
engaging multiple transactions at the same time. You must sell before buying again.
Example 3:
Input: [7,6,4,3,1]
Output: 0
Explanation: In this case, no transaction is done, i.e. max profit = 0.
解题思路:
- 由于没有限制买卖次数. 所以收益可以叠加.
- 就是要找到前面价格比后面低的位置.
- 然后一直叠加收益即可
class Solution {
public:
int maxProfit(vector<int>& prices)
{
if(prices.size() <= 1)
return 0;
int res = 0;
int len = prices.size();
for(int i = 0; i < len-1; i++)
{
if(prices[i] < prices[i+1])
{
res += prices[i+1] - prices[i];
}
}
return res;
}
};