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.
minSoFar
from the current stock price.maxProfit
, update maxProfit
with the new potential profit.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...
Main Function is not defined.
public static int maxProfit(vector<int>& prices){
int maxprofit = 0;
int minsofar = prices[0];
for(int i = 0; i < prices.size();i++){
minsofar = min(minsofar,prices[i]);
int profit = prices[i] - minsofar;
maxprofit = max(maxprofit, profit);
}
return maxprofit;
}//function end
Utility Function is not required.