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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
class Solution { public: int maxProfit(vector<int>& prices) { int minvalue = 99999999; int ans = 0; for(int i = 0; i < prices.size(); i++) { if(minvalue > prices[i]) { minvalue = prices[i]; } prices[i] = prices[i] - minvalue; if(ans < prices[i]) { ans = prices[i]; } } return ans; } }; |
❤ 点击这里 -> 订阅《PAT | 蓝桥 | LeetCode学习路径 & 刷题经验》by 柳婼