Smartphone

独家优惠奖金 100% 高达 1 BTC + 180 免费旋转




Solve the Best Time to Buy and Sell Stock Problem

You are given an integer array of prices where prices[i] is the price of a given stock on an ith day. Design an algorithm to find the maximum profit.

Some constraints are as follows:

Example 1:

Example 2:

The problem is to find out the maximum profit you can get for a stock during a certain period of time.

We have 2 states for a stock on a Day(i):

Hence, there are 3 possible actions you can take on Day(i):

Let’s rearrange the above into actions and states.
The goal is to calculate the max profit while making sure that the state (buy or sell) stays on that day and there is no transaction overlap.

Now let’s add the transaction count constraint.
The goal is to calculate the max profit while making sure that the state (buy or sell) stays on that day, there is no transaction overlap and the transaction count is within limits.

If we calculate the above states for all days and transaction counts, we will eventually find out the maximum profit on the last day with the Sell state. Sell should be the last state since we want a transaction that’s closed towards the end since a Buy at the end would be a wasteful loss of money.

The above O(n * k) solution works very well if k less than the maximum number of transactions possible.

But what if the transaction count was unlimited or in other words greater than the maximum number of mutually-exclusive transactions possible during those days? Can we do better?

A simpler solution for this case is to iterate through the days and start a transaction each time we see a local valley and sell on the local peak.

Buy and Sell

The following code implements the logic explained above in Java.
Buy state is represented with a 1 and Sell state with 0.

If you found this article useful, please help me reach more dev learners!

Show some ❤ by giving “claps” 👏 at the left margin of the page (on desktop) or at the bottom (on mobile). You can do so up to 50 times by clicking continuously!

Add a comment

Related posts:

WTF is Sedition?

The last four years have had a lot of legal experts looking up once-obscure terminology. Emoluments, insurrection, sedition. These are not words I learned in law school. But, here we are. As 2020…

Write for Social Science

Every time I went to a party in university and told someone that I studied psychology, at least one person would ask me, “So you can read minds?” Unfortunately, no. Still, there’s a lot of really…

Future in the First

Stepping foot on the freshly cut grass of campus, hearing the chattering of people in the lecture halls, and feeling the rush of a thousand different people going in and out of buildings are the…