买卖股票的最佳时机
这题的特点就是只能买卖股票一次: 在某一天买入然后在某一天卖掉
贪心解法: 这个比较容易理解, 就是取坐左边最小值, 然后取右边最大值, 直接拉代码
- class Solution {
- public int maxProfit(int[] prices) {
- int low = Integer.MAX_VALUE;
- int result = 0;
- for(int i = 0; i < prices.length; i++){
- //找到左边最小的
- low = Math.min(low, prices[i]);
- //直接取值
- result = Math.max(result, prices[i] - low);
- }
- return result;
- }
- }
动规:
- class Solution {
- public int maxProfit(int[] prices) {
- int len = prices.length;
- if(prices == null || len == 0){
- return 0;
- }
- //创建一个二维dp数组
- int[][] dp = new int[len + 1][2];
- //初始化
- dp[0][0] -= prices[0];
- dp[0][1] = 0;
- //开始遍历
- for(int i = 1; i < len; i++){
- //持有股票的情况
- dp[i][0] = Math.max(dp[i - 1][0], -prices[i]);
- //不持有股票的情况
- dp[i][1] = Math.max(dp[i - 1][1], prices[i] + dp[i - 1][0]);
- }
-
- return dp[len - 1][1];
- }
- }
也可以简化为一维数组版本
- class Solution {
- public int maxProfit(int[] prices) {
- int len = prices.length;
- if(len == 0 || prices == null){
- return 0;
- }
- int[] dp = new int[2];
- //一样进行初始化
- dp[0] -= prices[0];
- dp[1] = 0;
- //开始遍历, 这里往后推了一天
- for(int i = 1; i <= len; i++){
- //有股票: 之前就有/今天买的
- dp[0] = Math.max(dp[0], -prices[i - 1]);
- //无股票: 本来就没有, 和今天卖掉的
- dp[1] = Math.max(dp[1], prices[i - 1] + dp[0]);
- }
- return dp[1];
- }
- }
买卖股票的最佳时机II
上一题是只能买卖一次, 这里是可以无限买卖
贪心算法:
之前已经提过, 就是相当于每天都交易, 然后只要交易结果是正数就加起来
- class Solution {
- public int maxProfit(int[] prices) {
- int res = 0;
- for(int i = 1; i < prices.length; i++){
- res += Math.max(prices[i] - prices[i-1], 0);
- }
- return res;
- }
- }
动态规划:
这里的dp数组定义和上一题是一模一样的, 唯一不同的地方,就是推导dp[i][0]的时候,第i天买入股票的情况
第i天持有股票, 要么是之前就有, 要么是第i天才买, 对于后者: 需要用之前已经有的现金-第i天的price
第i天不持有股票, 要么是之前就无, 要么是第i天才卖掉, 对于后者: 也是今天价格+之前有的情况
- class Solution {
- public int maxProfit(int[] prices) {
- int len = prices.length;
- if(len == 0 || prices == null){
- return 0;
- }
- int[][] dp = new int[len + 1][2];
- dp[0][0] -= prices[0];
- dp[0][1] = 0;
- //开始遍历
- for(int i = 1; i < len; i++){
- //持有股票---之前就有/今天买的(要加上之前的钱)
- dp[i][0] = Math.max(dp[i - 1][0], -prices[i] + dp[i - 1][1]);
- //没有股票----之前就没/今天卖掉的
- dp[i][1] = Math.max(dp[i - 1][1], prices[i] + dp[i - 1][0]);
- }
-
- return dp[len - 1][1];
-
- }
- }
优化版, 记住两点:
- class Solution {
- public int maxProfit(int[] prices) {
- int len = prices.length;
- if(len == 0 || prices == null){
- return 0;
- }
- int[] dp = new int[2];
- dp[0] -= prices[0];
- dp[1] = 0;
- //开始遍历
- for(int i = 1; i <= len; i++){
- //持有股票---之前就有/今天买的(要加上之前的钱)
- dp[0] = Math.max(dp[0], -prices[i - 1] + dp[1]);
- //没有股票----之前就没/今天卖掉的
- dp[1] = Math.max(dp[1], prices[i - 1] + dp[0]);
- }
-
- return dp[1];
-
- }
- }