121. 买卖股票的最佳时机与122. 买卖股票的最佳时机 II
题目:
思路:
【1】121. 买卖股票的最佳时机的思路
【1.1】双指针的方式
本质上求得是右边某值减去左边某值的最大值是多少
所以双指针处理
输入示例:[7,1,5,3,6,4]
左指针left,右指针right一开始都是指向下标为0的数值
右指针right不断向右走
如当right = 1的时候,记录 之前的最大利润和现在的利润(right - left)哪个最大留哪个
由于left = 7 > right = 1,所以此时应该变更左指针的位置
因为right右边的其余值X,都会存在X-1>X-7
【2】122. 买卖股票的最佳时机 II的思路
【2.1】贪心的做法
因为本着可以多次买卖的做法
只要一有差价便赚其实就可以获得最大利润了
如[7,1,5,3,6,4]
7>1 故7的时候不应该买
1<5 故1的时候应该买然后第二天就买
5>3 故5的时候不应该买
3<6 故3的时候应该买然后第二天就买
...
依次类推,如果两天之间存在收益就应该买入并赚取差价,否则则不买
如此下来利润便是最大的
代码展示:
【1】121. 买卖股票的最佳时机的代码
//时间3 ms 击败 27.79% //内存57.9 MB 击败 32.90% //时间复杂度:O(n),只需要遍历一次。 //空间复杂度:O(1),只使用了常数个变量。 class Solution { public int maxProfit(int[] prices) { if (prices.length <= 1){ return 0; } int minPrices = prices[0] , result = 0; for (int i = 1; i < prices.length; i++){ minPrices = Math.min(minPrices,prices[i]); result = Math.max(result,(prices[i] - minPrices)); } return result; } } //时间2 ms击败 45.61% //内存57.8 MB 击败 42.18% class Solution { public int maxProfit(int[] prices) { int max = 0; int min = prices[0]; for(int i = 1;i<prices.length;i++){ if(prices[i] < min){ min = prices[i]; }else{ max = Math.max(max,prices[i]-min); } } return max; } }
【2】122. 买卖股票的最佳时机 II的代码
//时间1 ms击败 76.60% //内存43.3 MB 击败 9.2% class Solution { public int maxProfit(int[] prices) { int minPrices = prices[0] , maxPrices = prices[0] , result = 0; for (int i = 1; i < prices.length; i++){ if (prices[i] < maxPrices){ result += maxPrices - minPrices; minPrices = prices[i]; } maxPrices = prices[i]; if (i == prices.length-1){ result += maxPrices - minPrices; } } return result; } } //时间1 ms 击败 76.60% //内存43.3 MB 击败 14.36% class Solution { public int maxProfit(int[] prices) { int ans = 0; int n = prices.length; for (int i = 1; i < n; ++i) { ans += Math.max(0, prices[i] - prices[i - 1]); } return ans; } } //时间1 ms 击败 76.60% //内存43.2 MB 击败 22.71% class Solution { public int maxProfit(int[] prices) { int len = prices.length; if (len < 2){ return 0; } int res = 0; for (int i = 1; i < len; i++) { int diff = prices[i] - prices[i - 1]; if (diff > 0){ res += diff; } } return res; } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 25岁的心里话
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现