题目要求:
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.
分析:
本题可以这样理解,根据prices数组中前后两个元素之差得到差值数组,即得到前后两天的利润数组profit,此题就转化成了编程之美2.14、求数组的子数组之和的最大值的问题。
代码实现:
class Solution {
public:
int maxProfit(vector<int> &prices) {
if(prices.empty())
return 0;
int n=prices.size()-1;
int temp=prices[0];
int sum=0;
int profit=0;
for(int i=1;i<=n;i++)
{
sum+=(prices[i]-temp);
temp=prices[i];
if(sum<0)
{
sum=0;
}
if(sum>profit)
profit=sum;
}
return profit;
}
};