Best Time to Buy and Sell Stock II - Easy

less than 1 minute read

Published:

Question

  • https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/

You are given an array prices where prices[i] is the price of a given stock on the ith day.

Find the maximum profit you can achieve. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times).

Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).

Approach

  • Iteration
  • https://medium.com/algorithms-and-leetcode/best-time-to-buy-sell-stocks-on-leetcode-the-ultimate-guide-ce420259b323

Solution

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int min_num = prices[0];
        int max_num = INT_MIN;
        int ans = 0;
        int n = prices.size();
        for(int i=1; i<n; i++) {
            if(prices[i] > prices[i-1]) {
                ans+=(prices[i]-prices[i-1]);
            }
        }
        return ans;
    }
};