【LeetCode笔记】121. 买卖股票的最佳时机 / 剑指 Offer 63. 股票的最大利润(Java、动态规划)
生活随笔
收集整理的這篇文章主要介紹了
【LeetCode笔记】121. 买卖股票的最佳时机 / 剑指 Offer 63. 股票的最大利润(Java、动态规划)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
文章目錄
- 題目描述
- 代碼 & 思路
- 初版代碼
- 更新啦~優化代碼
- 再次更新
題目描述
- 講道理,一眼dp
代碼 & 思路
- 時間復雜度O(n),不過可改進的地方還多,跑出來大概6ms。
初版代碼
class Solution {public int maxProfit(int[] prices) {// 做啥:找一個i,j(j > i)且prices[j] > prices[i],使得 max = prices[j] - prices[i]// 用dp做吧int len = prices.length;if(len == 1){return 0;}// dp[i]代表當前值之后能遇到的最大值int[] dp = new int[len];dp[len-1] = 0;for(int i=len-2;i >= 0;i--){dp[i] = Math.max(prices[i+1],dp[i+1]);}int max = 0;for(int i=0;i<len-1;i++){max = Math.max(dp[i] - prices[i],max);}return max;} }更新啦~優化代碼
- 節約了空間,空間復雜度由 O(n) 變成了 O(1)
再次更新
class Solution {public int maxProfit(int[] prices) {int max = prices[prices.length - 1];int res = 0;for(int i = prices.length - 2; i >= 0; i--) {max = Math.max(max, prices[i + 1]);res = Math.max(max - prices[i], res);}return res;} }總結
以上是生活随笔為你收集整理的【LeetCode笔记】121. 买卖股票的最佳时机 / 剑指 Offer 63. 股票的最大利润(Java、动态规划)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python 修饰器 参数_具有参数的P
- 下一篇: 怎么制作游戏脚本_精彩的游戏视频混剪怎么