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.
这题和单纯的找到数组中最大值最小值不同。是因为我们要保证最小值在最大值前面。因此我们可以先找到i+1~n中最大值,在计算i与最大值的差值。遍历整个数组,找到差值最大的值。
class Solution {
public:
int maxProfit(vector<int> &prices) {
int n = prices.size();
if(n==0) return 0;
int ans = 0;
int maxPrice = prices[n-1];
for(int i = n-1;i>=0;i--)
{
maxPrice = max(prices[i],maxPrice);
ans = max(ans,maxPrice-prices[i]);
}
return ans;
}
};