Day 5 of 30-Day LeetCode Challenge

Aanchal Patial
1 min readApr 15, 2020

--

Say you have an array prices 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 (i.e., buy one and sell one share of the stock multiple times).

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

class Solution {
public:
int maxProfit(vector<int>& prices) {
int result = 0;
for(int i=0;i<prices.size();++i){
int num = prices[i];
int j = i+1;
while(j<prices.size()&&prices[j]>=num){
num = prices[j];
++j;

result += prices[j-1]-prices[i];
i = j-1;
}
return result;

}
};

--

--

Aanchal Patial

We never really grow up, we only learn how to act in public