Profit Maximization – Maximum Single-Sell Profit problem
Given an array of stock prices, where the increasing indexes of the array signify the increase in time. Return a good time to buy and sell such that profit is maximized.
Suppose we are given an array of n integers representing stock prices on a single day. We want to find a pair (buyDay, sellDay), with buyDay ≤ sellDay, such that if we bought the stock on buyDay and sold it on sellDay, we would maximize our profit.
For example, price = [23171, 21015, 21123, 21366, 21013, 21367] then maximum single sell profit will be price[5] – price[4] = 21367 – 21013 = 354.
We can solve it by some modification to Kadane's Algorithm described here in my previous post.
Kadane's Algorithm
Basically we keep keep track of minimum price so far to buy and maximum price so far so that profit (buy-sell) is maximized ate that point. Below is a simple implementation of this approach i O(n) time and o(1) space.
Read full article from Profit Maximization - Maximum Single-Sell Profit problem - Algorithms and Problem SolvingAlgorithms and Problem Solving
No comments:
Post a Comment