Best Time to Buy and Sell Stock II
1 min readJun 7, 2019
Question: 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 (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).
You may view the full question here.
Approach 1: The solution here elaborates three different approaches. Let’s check the one pass solution. The code looks like this —
//Approach 1:
//Runtime: 1ms
//Memory usage: 37MBclass Solution {
public int maxProfit(int[] prices) {
int diff = 0;
for(int i = 1; i<prices.length; i++){
if(prices[i]>prices[i-1]){
diff += prices[i]-prices[i-1];
}
}
return diff;
}
}
Find more posts here.
Cheers & Chao!