【问题描述】[简单]
【解答思路】
1. 暴力
时间复杂度:O(N^2) 空间复杂度:O(1)
public class Solution {public int maxProfit(int prices[]) {int maxprofit = 0;for (int i = 0; i < prices.length - 1; i++) {for (int j = i + 1; j < prices.length; j++) {int profit = prices[j] - prices[i];if (profit > maxprofit)maxprofit = profit;}}return maxprofit;}
}
2. 动态规划/哨兵思想
解释一
时间复杂度:O(N) 空间复杂度:O(1)
public class Solution {public int maxProfit(int prices[]) {int minprice = Integer.MAX_VALUE;int maxprofit = 0;for (int i = 0; i < prices.length; i++) {if (prices[i] < minprice)minprice = prices[i];else if (prices[i] - minprice > maxprofit)maxprofit = prices[i] - minprice;}return maxprofit;}
}
解释二
public int maxProfit(int[] prices) {if(prices.length == 0) return 0;int max=0;int min=prices[0];int[] dp=new int[prices.length];for(int i=1;i<prices.length;i++){min=Math.min(prices[i],min); //一直找最小的值dp[i]=Math.max(dp[i-1],prices[i]-min);}return dp[prices.length-1];}
class Solution {public int maxProfit(int[] prices) {int cost = Integer.MAX_VALUE, profit = 0;for(int price : prices) {cost = Math.min(cost, price);profit = Math.max(profit, price - cost);}return profit;}
}
【总结】
1.动态规划流程
第 1 步:设计状态
第 2 步:状态转移方程
第 3 步:考虑初始化
第 4 步:考虑输出
第 5 步:考虑是否可以状态压缩
2. 暴力逐步优化 思想要到位
转载链接:https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock/solution/121-mai-mai-gu-piao-de-zui-jia-shi-ji-by-leetcode-/
参考链接:https://leetcode-cn.com/problems/gu-piao-de-zui-da-li-run-lcof/solution/mian-shi-ti-63-gu-piao-de-zui-da-li-run-dong-tai-2/