121. Best Time to Buy and Sell Stock
Last updated
Last updated
this one: buy one, sell once, so we focus on max profit!
time: O(n)
space: O(1)
class Solution {
public int maxProfit(int[] prices) {
// so find min, in the same loop, because profit gen after chosing min
// and find max profit = price - min
int min = Integer.MAX_VALUE;
int profit = 0;
for (int price : prices) {
if (min > price) {
min = price;
}
if (price - min > profit) {
profit = price - min;
}
}
return profit;
}
}
class Solution {
public int maxProfit(int[] prices) {
int min = Integer.MAX_VALUE;
int res = 0;
for (int price : prices) {
min = Math.min(min, price);
res = Math.max(res, price - min);
}
return res;
}
}
/*
[7,1,5,3,6,4]
m o
[7,1,7,3,2,7]
*/
time: O(n)
space: O(n)
class Solution {
public int maxProfit(int[] prices) {
int n = prices.length;
int dp[][] = new int[n][2];
// dp means max profit
dp[0][0] = 0; // no stock
dp[0][1] = -prices[0]; // has stock
for (int i = 1; i < prices.length; i++) {
// 1. keep no stock 2. has stock and sell
dp[i][0] = Math.max(dp[i-1][0], dp[i-1][1] + prices[i]);
// only one sell, so we buy only once,
// only dp[0][0] can represent no stock!
dp[i][1] = Math.max(dp[0][0] - prices[i], dp[i-1][1]);
}
return dp[n-1][0];
}
}