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.
Difficulty:Medium
class Solution {
public:
int maxProfit(vector<int>& prices) {
int len = prices.size();
if(len==1||len==0)
return 0;
vector<int> nums(len,0);
nums[len-1] = prices[len-1];
for(int i = len-2;i>=0;i--)
nums[i] = max(nums[i+1],prices[i]);
int ans = -2147483647;
for(int i = 0;i<len;i++)
ans = max(ans,nums[i]-prices[i]);
return ans;
}
};