一 题目
在数组里面找两个数之差最大,同时大的数比小的数位置靠后。如果没有这样的两个数,返回0。
二 代码
- 解法一(三个解法中的最佳解法)
这题用到了滑动窗口的思想,minnum的索引类似于左指针,i为右指针,
每次循环,用minnum记录数组[0...i]中最小的数字,用profit记录数组[0...i]中最大利润。
随着i指针的不断右滑,不断判断更新profit。
最终profit中存储最大值。
let maxProfit=function(prices){
let profit=0;
let minnum=prices[0];
for(let i=0;i<prices.length;i++){
minnum=Math.min(minnum,prices[i]);
profit=Math.max(profit,prices[i]-minnum);
}
return profit;
}
- 解法二
思路基本同上
//动态规划
let maxProfit=function(prices){
if(prices.length<2) return 0;
let minnum=prices[0];
let dp=[];
dp[0]=prices[1]-prices[0];
for(let i=1;i<prices.length;i++){
minnum=Math.min(minnum,prices[i]);
dp[i]=Math.max(dp[i-1],prices[i]-minnum);
}
dp[dp.length]=0;
return Math.max(...dp);
}
- 解法三
相较于暴力法比较所有的(i,j),这个方法只比较满足i<j条件的(i,j)
//不那么暴力的暴力解法
let maxProfit = function(prices) {
if(prices.length<2) return 0;
let l=0;
let profit=0;
for(let r=1;r<prices.length;r++){
l=0;
while(l<r){
profit=Math.max(prices[r]-prices[l],profit);
l++;
}
}
return profit;
};