当前位置: 首页 > news >正文

LeetCode算法题---第3天

注:大佬解答来自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.大佬解答

 

http://www.lryc.cn/news/177698.html

相关文章:

  • 欧洲FBA专线海运与陆运的差别
  • UDS诊断
  • 计算材料学学习记录1
  • PHP8中的构造方法和析构方法-PHP8知识详解
  • 【GPU编程】Visual Studio创建基于GPU编程的项目
  • MySQL面试题-索引的基本原理及相关面试题
  • MySQL学习笔记19
  • 为什么u盘在mac上显示不出来
  • 【golang】调度系列之sysmon
  • 货物寄到英国选择什么物流比较划算?
  • vite + react 基本项目搭建
  • 一个方法解决三道区间问题
  • sub0 里斯本精彩回顾:探索波卡区块的创新空间
  • 颜色+情感的英语表达还有这些,零基础学英语口语去哪里,柯桥有推荐的吗?
  • exoplayer的使用-6,播放器的选择
  • Windows上安装 Go 环境
  • 【设计模式】四、工厂模式
  • 十九,镜面IBL--BRDF积分贴图
  • Linux 创建 终止线程(thread)
  • 【IPC 通信】信号处理接口 Signal API(6)
  • ipaguard界面概览
  • 萌新的FPGA学习绪论-1
  • 目标检测算法改进系列之Backbone替换为EMO
  • Laravel一些优雅的写法
  • vue+three.js中使用Ammo.js
  • 【k8s】kubectl命令详解
  • Centos 7 部署SVN服务器
  • SEO方案尝试--Nuxtjs项目基础配置
  • 【算法分析与设计】动态规划(上)
  • Java多线程篇(6)——AQS之ReentrantLock