第一题:
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.
解法非常简单:从前往后扫描,记录最小的buy time,和最大的价格差。class Solution {
public:
int maxProfit(vector<int> &prices) {
if(prices.size() < 2)
return 0;
int maxprofit = 0;
int buyprice = prices[0];
for(int i=1; i<prices.size(); ++i)
{
maxprofit = max(maxprofit, prices[i]-buyprice);
buyprice = min(buyprice, prices[i]);
}
return maxprofit;
}
};
Method 2: 利用差分数列,求最大的连续子序列和。
参考: http://www.geeksforgeeks.org/largest-sum-contiguous-subarray/
class Solution {
public:
int maxProfit(vector<int> &prices) {
if(prices.size() < 2) return 0;
int profit = 0;
int cur_max = prices[1]-prices[0];
profit = cur_max;
int diff = 0;
for(int i=2; i<prices.size(); i++)
{
diff = prices[i] - prices[i-1];
cur_max = max(diff, cur_max+diff);
profit = max(cur_max, profit);
}
return max(profit,0);
}
};
第二题:
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).
每次在上升序列开始时买入,在上升序列结束时卖出。然后在下一个上升序列开始时再买入........从头到尾扫描prices,如果i比i-1大,那么price[i] – price[i-1]就可以计入最后的收益中。这样扫描一次O(n)就可以获得最大收益了。
class Solution {
public:
int maxProfit(vector<int> &prices) {
int sum = 0;
for(int i=1; i<prices.size(); ++i)
{
if(prices[i] > prices[i-1])
sum += (prices[i] - prices[i-1]);
}
return sum;
}
};