注:大佬解答来自LeetCode官方题解
121.买卖股票的最佳时期
1.题目
2.个人解答
function maxProfit(prices) {
//更新最低价格和最大利润
let minPrice = prices[0];
let maxProfit = 0;
for (let i = 1; i < prices.length; i++) {
// 如果当前价格比最低价格还低,更新最低价格
if (prices[i] < minPrice) {
minPrice = prices[i];
}
// 计算当前价格卖出时的利润,并更新最大利润
else if (prices[i] - minPrice > maxProfit) {
maxProfit = prices[i] - minPrice;
}
}
return maxProfit;
}
3.大佬解答
122.买卖股票最佳时期Ⅱ
1.题目
2.个人解答
var maxProfit = function (prices) {
//更新最低价格和最大利润
let minPrice = prices[0];
let maxProfit = 0;
for (let index = 1; index < prices.length; index++) {
if (prices[index] < minPrice) {
minPrice = prices[index];
} else {
maxProfit += prices[index]-minPrice;
minPrice=prices[index]
}
}
return maxProfit
};
3.大佬解答
var maxProfit = function(prices) {
const n = prices.length;
let dp0 = 0, dp1 = -prices[0];
for (let i = 1; i < n; ++i) {
let newDp0 = Math.max(dp0, dp1 + prices[i]);
let newDp1 = Math.max(dp1, dp0 - prices[i]);
dp0 = newDp0;
dp1 = newDp1;
}
return dp0;
};
var maxProfit = function(prices) {
let ans = 0;
let n = prices.length;
for (let i = 1; i < n; ++i) {
ans += Math.max(0, prices[i] - prices[i - 1]);
}
return ans;
};
55.跳跃游戏
1.题目
2.个人解答
function canJump(nums) {
let maxReach = 0;
for (let i = 0; i < nums.length; i++) {
if (i > maxReach) {
return false; // 如果当前位置无法到达,则返回false
}
maxReach = Math.max(maxReach, i + nums[i]); // 更新maxReach
}
return maxReach >= nums.length - 1;
}
3.大佬解答