function maxProfit(prices: number[]): number {
let res = 0, prev = Infinity;
for (let i = 0; i < prices.length; i++) {
res = Math.max(res,prices[i] - prev);
prev = Math.min(prev,prices[i]);
}
return res;
};
class Solution {
public int maxProfit(int[] prices) {
int min = Integer.MAX_VALUE;
int max = 0;
for(int i = 0; i < prices.length; i++){
if(prices[i] < min){
min = prices[i];
}else{
max = Math.max(max, prices[i] - min);
}
}
return max;
//时间复杂度:O(n)
//空间复杂度:O(1)
}
}
共以下 10 个回答
时间O(n),空间O(1)
基础中的基础题
时间复杂度:O(n)
空间复杂度:O(n)
class Solution {
public int maxProfit(int[] prices) {
//记录上一个最大利润值 要么取上一个,要么自己-min
int dp[]=new int[prices.length+1];
if(prices.length0||prices
null)
{
return 0;
}
int min = prices[0];
dp[0]=0;
for(int i=1;i<dp.length;i++)
{
dp[i]=Math.max(dp[i-1],prices[i-1]-min);
min=Math.min(min,prices[i-1]);
}
return dp[dp.length-1];
}
}
8.6
Day27:下面是代码