You are given an array prices where prices[i] is the price of a given stock on the ith day.
You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock.
Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0.
class Solution {
public:
int maxProfit(vector<int>& prices) {
int n=prices.size(),ans;
int minnum=100010;
for(int i=0;i<n;i++){
minnum=min(minnum,prices[i]);
ans=max(ans,prices[i]-minnum);
}
return ans;
}
};
tip 记下每次遍历的最小值,用当前的price[i]-minnum来表示第i天可获的profits,max更新最大值。