Best Time to Buy and Sell Stock
链接:https://oj.leetcode.com/problems/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.
解法:
此题比较简单,一遍扫描就OK了,记录到目前为止的一个最小price和最大收益,没次于这个price比较,如果小于该值则更新,如果大于该值且差值大于最大收益,则更新最大收益。
代码如下:
int maxProfit(vector<int> &prices) {
int len = prices.size();
if(len == 0) return 0;
int min = prices[0];
int max = 0;
for(int i=1; i < len; ++i)
{
if(prices[i] < min)
{
min = prices[i];
}else{
int temp = prices[i] - min;
if( max < temp )
max = temp;
}
}
return max;
}
Best Time to Buy and Sell Stock II
链接:
https://oj.leetcode.com/problems/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).
解法:
通过分析发现,以每一个连续上升区间为一次交易,则总的收益最大。
代码如下:
int maxProfit(vector<int> &prices) {
int len = prices.size();
if(len == 0) return 0;
int min = prices[0];
int pre = prices[0];
int max = 0;
for(int i=0; i < len; ++i)
{
if( prices[i] <= pre )
{
max += pre -min;
min = prices[i];
pre = prices[i];
}else{
pre = prices[i];
}
}
if(pre > min)
max += pre - min;
return max;
}
Best Time to Buy and Sell Stock III
链接:https://oj.leetcode.com/problems/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).
解法:
两遍扫描即可,第一次扫描,借助一个等大小的数组存储到i位置交易一次的最大收益。
第二次扫描从后往前扫描,计算从该节点到最后 交易一次的最大收益, 如果该最大收益加上第一遍扫描时到该位置之前的位置后一次交易的最大值 大于 当前的最大值, 则更新最大值。
两遍扫描即得最后答案。
本体注意边界条件,两次扫描别落项也别数组越界了。
代码如下:
int maxProfit(vector<int> &prices) {
int len = prices.size();
if(len <= 1) return 0;
if(len == 2)
{
if( prices[1] - prices[0] > 0)
return prices[1] - prices[0];
else
return 0;
}
vector<int> profit(len, 0);
int tempMax= 0;
int minPrice = prices[0];
for(int i=1; i < len; ++i)
{
int temp = prices[i] - minPrice;
if( temp > 0){
if( temp > tempMax)
tempMax = temp;
profit[i] = tempMax;
}else
minPrice = prices[i];
}
tempMax = 0;
int maxProfit = profit[len-1];
int maxPrice = prices[len - 1];
for(int i= len-1; i > 0; --i)
{
int temp = maxPrice- prices[i];
if( temp <= 0)
{
maxPrice= prices[i];
temp = 0;
}
if(temp > tempMax )
tempMax = temp;
if(tempMax + profit[i - 1] > maxProfit)
maxProfit = tempMax + profit[i-1];
}
return maxProfit;
}