
This is an array interview question that is solved using Python Language.
Below, you are given an integer array prices
where prices[i]
is the price of a given stock on the ith
day.
On each day, you may decide to buy and/or sell your stock. You can only get to hold at most one share of the stock at any time. However, you can buy it again immediately and get to sell it on the same day.
Now, find and return the maximum profit you can achieve.
Input: prices = [7,1,5,3,6,4] Output: 7 Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4. Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3. Total profit is 4 + 3 = 7.
Now, we have to come up with an algorithm to find the maximum profit. So if the given prices are [7,1,5,3,6,4], then the result will be 7, as we will buy on day 2 (price 1), then sell on day 3, (price 5), so profit is 5 – 1 = 4. Now but on day 4 (price 3), and sell on day 5 (price 6) so profit is 6 – 3 = 3.
Example Let us see the following implementation to get better understanding:
Solution 1:
class Solution(object):
def maxProfit(self, prices):
if not prices:
return 0
n = len(prices)
dp = [0 for i in range(n)]
answer = 0
ymin = prices[0]
for i in range(1,n):
ymin = min(ymin,prices[i])
dp[i] = max(dp[i],prices[i]-ymin)
answer = max(answer,dp[i])
zmax = [0 for i in range(n)]
zmax[-1] =prices[-1]
tempp = 0
for i in range(n-2,-1,-1):
zmax[i] = max(zmax[i+1],prices[i])
zmin = [prices[-1],n]
for i in range(n-2,-1,-1):
tempp = max(tempp,zmax[i+1]-prices[i+1])
answer = max(answer,dp[i]+tempp)
return answer
obj = Solution()
print(obj.maxProfit([7,1,5,3,6,4]))
Solution 2:
class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
answer = 0
for i in range(1,len(prices)):
if prices[i] - prices[i-1] >0:
answer+=(prices[i] - prices[i-1])
return answer
ob1 = Solution()
print(ob1.maxProfit([7,1,5,3,6,4]))
If you have any question or comments, do not hesitate to ask us.
Quote: The moon looks upon many night flowers; the night flowers see but one moon. – Jean Ingelow