![]() |
VOOZH | about |
Efficient approach: If we are allowed to buy and sell only once, then we can use following algorithm. Maximum difference between two elements. Here we are allowed to buy and sell multiple times.
Following is the algorithm for this problem.
Output:
Buy on day: 0 Sell on day: 3 Buy on day: 4 Sell on day: 6
Time Complexity: The outer loop runs till I become n-1. The inner two loops increment value of I in every iteration. So overall time complexity is O(n)
Auxiliary Space: O(1) since using constant variables
Please refer complete article on Stock Buy Sell to Maximize Profit for more details!