Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- http://leetcode.com/onlinejudge#question_121
- Best Time to Buy and Sell Stock
- 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.
- */
- class Solution {
- public:
- int maxProfit(vector<int> &prices) {
- const size_t N = prices.size();
- if(N <= 1) { return 0; }
- int minSoFar = prices[0];
- int maxProfit = 0;
- for(size_t i = 1; i < N; ++i)
- {
- if(prices[i] < minSoFar) { minSoFar = prices[i]; }
- else{ maxProfit = max(maxProfit, prices[i] - minSoFar); }
- }
- return maxProfit;
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment