AlgoMaster Logo

Best Time to Buy and Sell Stock II

Ashish

Ashish Pratap Singh

medium

Problem Description

Approaches

1. Greedy Approach

Intuition:

The problem is essentially about finding opportunities to make as much profit as possible by buying stocks on one day and selling them on another. This can be achieved by making transactions whenever there's a profit to be made, without concern for a future decrement in prices.

In a simplified manner, the problem reduces to accumulating all positive differences between consecutive days. By always projecting into the future and accumulating possible gains daily, we capitalize on every rising curve of the stock price graph.

Code:

Example Walkthrough:

0
7
1
1
2
5
3
3
4
6
5
4
maxProfit = 0
Step 1 / 5

2. Peak Valley Approach

Another way to look at this problem is to find every consecutive pair of peaks and valleys. A peak-to-valley traversal adds the difference from each peak to its preceding valley to determine the overall profit through multiple transactions.

Intuition:

This approach mimics the real-world scenario of buying stock at valleys (local minimums) and selling it at peaks (local maximums). This enables capturing every increasing sequence even if the overall curve spans over several days.

Code: