한 번의 거래로 낼 수 있는 최대 이익을 산출하라.
Input: prices = [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell.
Input: prices = [7,6,4,3,1]
Output: 0
Explanation: In this case, no transactions are done and the max profit = 0.
class Solution {
public:
int maxProfit(vector<int>& prices) {
int sum = 0;
int smallnum = prices[0];
for (auto iter = prices.begin()+1; iter != prices.end(); ++iter)
{
smallnum = min(smallnum, *iter);
sum = max(sum, *iter - smallnum);
}
return sum;
}
};
int smallnum = prices[0];
for (auto iter = prices.begin()+1; iter != prices.end(); ++iter)
{
smallnum = min(smallnum, *iter);
sum = max(sum, *iter - smallnum);
}
Runtime 138 ms / Memory 93.5 MB
https://leetcode.com/problems/best-time-to-buy-and-sell-stock/submissions/887967256/
https://leetcode.com/problems/best-time-to-buy-and-sell-stock/