Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Best Time to Buy and Sell Stock II
- http://leetcode.com/onlinejudge#question_122
- Say you have an array for which the ith element is the price of a given stock on day i.
- Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
- */
- class Solution {
- public:
- int maxProfit(vector<int> &prices) {
- const size_t N = prices.size();
- if(N <= 1) { return 0; }
- prices.push_back(0);
- int minSoFar = prices[0];
- int maxSoFar = prices[0];
- int profit = 0;
- for(size_t i = 1; i < prices.size(); ++i)
- {
- int p = prices[i];
- if(p < maxSoFar)
- {
- profit += max(0,maxSoFar - minSoFar);
- minSoFar = maxSoFar = p;
- }
- else if(p < minSoFar)
- {
- minSoFar = maxSoFar = p;
- }
- else if(p > maxSoFar)
- {
- maxSoFar = p;
- }
- }
- return profit;
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment