Objective:
To determine the maximum profit that can be achieved from buying and selling stock on given days, where the price of the stock is provided as an array.
Use a for loop to iterate through the array of stock prices.
minSoFar from the current stock price.maxProfit, update maxProfit with the new potential profit.Additionally, update minSoFar to be the minimum of its current value and the current stock price. This ensures that you always have the lowest price encountered up to the current day.
maxProfit will hold the maximum profit achievable by buying and selling the stock.Input:
prices = [7, 1, 5, 3, 6, 4]
Output:
Maximum Profit = 5
Explanation:
Input:
prices = [7, 6, 4, 3, 1]
Output:
Maximum Profit = 0
Explanation:
Input:
prices = [1, 2, 3, 4, 5]
Output:
Maximum Profit = 4
Explanation:
Input:
prices = [3, 2, 6, 5, 0, 3]
Output:
Maximum Profit = 4
Explanation:
def maxProfit(prices):
maxProfit = 0
minSoFar = prices[0]
for price in prices:
maxProfit = max(maxProfit, price - minSoFar)
minSoFar = min(minSoFar, price)
return maxProfit
https://leetcode.com/problems/pascals-triangle/description/
Loading component...
Loading component...