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 (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.
Example 1:
Input: [7, 1, 5, 3, 6, 4] Output: 5 max. difference = 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 In this case, no transaction is done, i.e. max profit = 0.
解析:最多进行一次交易使得利润最大化,假设在第k天卖出,必然是在前k-1天中最低价买入利润最大,时间复杂度为O(n).
<span style="font-family:SimSun;font-size:14px;">class Solution {
public:
int maxProfit(vector<int>& prices) {
if(!prices.size()) return 0;
int min = prices[0], max = 0, s = prices.size();
for(int i=1; i<s; i++)
{
if(prices[i] - min > max) max = prices[i] - min;
if(prices[i] < min) min = prices[i];
}
return max;
}
};</span>
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 (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).
解析:可以进行任意多次交易,因此只要在前后两天股票价值上涨时先后进行买入以及售出即可利润最大化,时间复杂度为O(n).
class Solution {
public:
int maxProfit(vector<int>& prices) {
if(!prices.size()) return 0;
int sum = 0, s = prices.size();
for(int i=0; i<s-1; i++)
if(prices[i] < prices[i+1]) sum += prices[i+1] - prices[i];
return sum;
}
};
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 at most two transactions.
解析:最多进行两次交易使得利润最大化。与Ⅰ类似的,只需将时间分成两段,计算前后两个时间段[1, i]和[i, n] (1<= i <=n)分别最多进行一次交易的最大利润之和,而计算[i, n] 时间段内利润最大值方法类似于计算[1, i]中利润最大值。不过对于本题,倘若循环的每次都对前后两个时间段分别进行一次计算将会导致超时,因此可以预先计算,从而使得时间复杂度依旧为O(n).
class Solution {
public:
vector<int> M1, M2;
int maxProfit(vector<int>& prices) {
if(prices.size() <=1 ) return 0;
int max = 0, temp, s = prices.size()-1, m;
for(m=1; m<=s; m++)
if(prices[m] > prices[m-1]) break;
if(m > s) return 0;
Max1(prices, m-1, s, M1);
Max2(prices, m, s+1, M2);
for(int i=m; i<=s; i++)
{
temp = M1[i-m] + M2[s-i];
if(temp > max) max = temp;
}
return max;
}
void Max1(vector<int> prices, int x, int y, vector<int>& M)
{
int min = prices[x], max = 0, temp;
for(int i=x+1; i<=y; i++)
{
temp = prices[i] - min;
if(temp > max) max = temp;
if(prices[i] < min) min = prices[i];
M.push_back(max);
}
}
void Max2(vector<int> prices, int x, int y, vector<int>& M)
{
M.push_back(0);
int max = prices[y-1], max2 = 0, temp;
for(int i=y-1; i>x; i--)
{
temp = max - prices[i];
if(temp > max2) max2 = temp;
if(prices[i] > max) max = prices[i];
M.push_back(max2);
}
}
};
Best Time to Buy and Sell Stock Ⅳ
占坑。。