Problem of The Day: Best Time to Buy and Sell Stock
Problem Statement
Solution [TLE]
public class Solution {
public int MaxProfit(int[] prices) {
int result = 0;
for (int i = 0; i < prices.Length - 1; i++) {
for (int j = i + 1; j < prices.Length; j++) {
result = Math.Max(result, prices[j] - prices[i]);
}
}
return result;
}
}
Solution [Accepted]
public class Solution {
public int MaxProfit(int[] prices) {
int result = 0;
int minPrice = int.MaxValue;
int maxPrice = int.MinValue;
foreach(int price in prices) {
minPrice = Math.Min(price, minPrice);
result = Math.Max(result, price - minPrice);
}
return result;
}
}
Time: O(n) Space: O(1)
Editorial
Approach 2: One Pass
class Solution:
def maxProfit(self, prices: List[int]) -> int:
min_price = float("inf")
max_profit = 0
for i in range(len(prices)):
if prices[i] < min_price:
min_price = prices[i]
elif prices[i] - min_price > max_profit:
max_profit = prices[i] - min_price
return max_profit
public class Solution {
public int MaxProfit(int[] prices) {
int minprice = int.MaxValue;
int maxprofit = 0;
for (int i = 0; i < prices.Length; i++) {
if (prices[i] < minprice)
minprice = prices[i];
else if (prices[i] - minprice > maxprofit)
maxprofit = prices[i] - minprice;
}
return maxprofit;
}
}
Leave a comment