股票问题
121.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.
class Solution {
public:
int maxProfit(vector<int>& prices) {
int n = prices.size();
if(n<=0)
return 0;
int minPrice = prices[0];
int profit = 0;
for(int i=1;i<n;i++)
{
minPrice = min(minPrice,prices[i]);
profit = max(profit,prices[i]-minPrice);
}
return profit;
}
};
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 (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).
class Solution {
public:
int maxProfit(vector<int>& prices) {
int n = prices.size();
if(n<=0)
return 0;
int index = 0;
int sum = 0;
int i;
for(i=1;i<n;i++)
{
if(prices[i-1]>prices[i]) // 如果股票价格开始下降
{
sum += prices[i-1] - prices[index];
index = i;
}
}
if(prices[i-1]>prices[index]) //若从index开始单调递增
sum += prices[i-1] - prices[index];
return sum;
}
};
123.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 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).
class Solution {
public:
int maxProfit(vector<int>& prices) {
int n = prices.size();
if(n<=1)
return 0;
vector<int> foreword(n,0);
vector<int> back(n,0);
vector<int> rec(n,0);
int low = prices[0];
int high = prices[n-1];
for(int i=1;i<n;i++)
{
low = min(low,prices[i]);
foreword[i] = max(prices[i]-low,foreword[i-1]);
}
for(int i=n-2;i>=0;i--)
{
high = max(high,prices[i]);
back[i] = max(high-prices[i],back[i+1]);
}
int maxP = -1;
for(int i=0;i<n;i++)
{
rec[i] = foreword[i] + back[i];
if(rec[i]>maxP)
maxP = rec[i];
}
return maxP;
}
};