Advertisement
Guest User

Best Time to Buy and Sell Stock II

a guest
Apr 10th, 2020
380
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.44 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     int maxProfit(vector<int>& prices) {
  4.         int answer = 0, minPrice = prices[0];
  5.         for (int i = 1; i < prices.size(); i++) {
  6.             if (prices[i-1] > prices[i]) {
  7.                 // sequence stopped increasing
  8.                 answer += (prices[i-1] - minPrice);
  9.                 minPrice = prices[i];
  10.             }
  11.         }
  12.         return answer + (prices[prices.size()-1] - minPrice);
  13.     }
  14. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement