[Solved] Maximum Profit by Buying and Selling Stocks Shares

[Solved] Maximum Profit by Buying and Selling Stocks Shares

Coding challenge: You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock.

This coding question was asked in the HackerEarth coding interview.

Solution

You don’t need any fancy data structure or algorithm to solve this problem. Stick with a basic array/list and some conditional checks.

Prerequisite:

Python code:

def return_max_profit(prices):
    out = 0
    curr_buy = prices[0]
    i=1
    while i < len(prices)-1:
        if prices[i] < curr_buy:
            curr_buy = prices[i]
            i+=1
        else:
            if prices[i] > prices[i+1]:
                print(f"Buy at {curr_buy} & sell at {prices[i]}.")
                out += (prices[i]-curr_buy)
                curr_buy = prices[i+1]
                i+=2
            else:
                i+=1
    return out


prices = [7,1,5,3,6,4]
print(f"Maximum Profit: {return_max_profit(prices)}")

Output:

Buy at 1 & sell at 5.
Buy at 3 & sell at 6.
Maximum Profit: 7

The code looks self-explanatory. Still, if you have any doubts, let’s discuss them in the comment section below.

Try to solve this coding challenge in any other programming language like C/C++, Java, etc. And share your solution with others here.

Leave a Reply

Your email address will not be published. Required fields are marked *