赞
踩
题目链接: 买卖股票的最佳时机 II
解题思路: 低买高卖
解题代码:
var maxProfit = function (prices) {
let result = 0;
for (let i = 1; i < prices.length; i++) {
result += Math.max(prices[i] - prices[i - 1], 0);
}
return result;
};
题目链接: 跳跃游戏
解题思路:
解题代码:
var canJump = function (nums) {
let cover = 0;
if (nums.length === 1) return true;
for (let i = 0; i <= cover; i++) {
cover = Math.max(i + nums[i], cover);
if (cover >= nums.length - 1) return true;
}
return false;
};
题目链接: 跳跃游戏 II
解题思路:
解题代码:
var jump = function (nums) {
let curDistance = 0; // 当前覆盖的最远距离的下标
let ans = 0; // 记录走的最大步数
let nextDistance = 0;// 下一步覆盖的最远距离的下标
for (let i = 0; i < nums.length - 1; i++) {
nextDistance = Math.max(nums[i] + i, nextDistance);
if (i === curDistance) {
curDistance = nextDistance;
ans++;
}
}
return ans;
};
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。