ভিডিওতে দেখো — YouTube @algonur_com
কোড
Python
def maxProfit(prices: list[int]) -> int:
minPrice, maxProfit = float('inf'), 0
for p in prices:
minPrice = min(minPrice, p)
maxProfit = max(maxProfit, p - minPrice)
return maxProfitJava
public int maxProfit(int[] prices) {
int min = Integer.MAX_VALUE, profit = 0;
for (int p : prices) {
min = Math.min(min, p);
profit = Math.max(profit, p - min);
}
return profit;
}Kotlin
fun maxProfit(prices: IntArray): Int {
var min = Int.MAX_VALUE; var profit = 0
for (p in prices) { min = minOf(min, p); profit = maxOf(profit, p - min) }
return profit
}C++
int maxProfit(vector<int>& prices) {
int minP = INT_MAX, profit = 0;
for (int p : prices) { minP = min(minP, p); profit = max(profit, p - minP); }
return profit;
}C
int maxProfit(int* prices, int n) {
int minP=prices[0], profit=0;
for(int i=1;i<n;i++){if(prices[i]<minP)minP=prices[i];int p=prices[i]-minP;if(p>profit)profit=p;}
return profit;
}জটিলতা
O(n)
সময় — অ্যারেটা একবারই ঘুরি, ম্যাপে খোঁজা O(1)।
O(1)
জায়গা — সবচেয়ে খারাপ ক্ষেত্রে সব সংখ্যা ম্যাপে থাকে।
আগের সমস্যা← Trapping Rain Waterপরের সমস্যাLongest Substring Without Repeating Characters →