美文网首页Android技术知识
Day60 买卖股票的最佳时机II

Day60 买卖股票的最佳时机II

作者: Shimmer_ | 来源:发表于2021-03-28 21:05 被阅读0次

给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。设计一个算法来计算你所能获取的最大利润。你可以尽可能地完成更多的交易(多次买卖一支股票)

https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-ii/

示例1:

输入: [7,1,5,3,6,4]
输出: 7
解释: 在第 2 天(股票价格 = 1)的时候买入,在第 3 天(股票价格 = 5)的时候卖出, 这笔交易所能获得利润 = 5-1 = 4 。
随后,在第 4 天(股票价格 = 3)的时候买入,在第 5 天(股票价格 = 6)的时候卖出, 这笔交易所能获得利润 = 6-3 = 3 。

示例2:

输入: [1,2,3,4,5]
输出: 4
解释: 在第 1 天(股票价格 = 1)的时候买入,在第 5 天 (股票价格 = 5)的时候卖出, 这笔交易所能获得利润 = 5-1 = 4 。
注意你不能在第 1 天和第 2 天接连购买股票,之后再将它们卖出。
因为这样属于同时参与了多笔交易,你必须在再次购买前出售掉之前的股票。

实例3:

输入: [7,6,4,3,1]
输出: 0
解释: 在这种情况下, 没有交易完成, 所以最大利润为 0。

提示:

1 <= prices.length <= 3 * 10 ^ 4
0 <= prices[i] <= 10 ^ 4

Java解法

思路:

  • 实际上昨天的解法上对卖出方式的处理变化,大体一致
  • 在这里需要截取每一段上升趋势,一旦下降就进行卖出
package sj.shimmer.algorithm.m3_2021;

/**
 * Created by SJ on 2021/3/27.
 */

class D60 {
    public static void main(String[] args) {
        System.out.println(maxProfit(new int[]{7, 1, 5, 3, 6, 4}));
        System.out.println(maxProfit(new int[]{1,2,3,4,5}));
        System.out.println(maxProfit(new int[]{7, 6, 4, 3, 1}));
    }


    public static int maxProfit(int[] prices) {
        int result = 0;
        if (prices != null && prices.length > 1) {
            int length = prices.length;
            int in = 0;
            for (int i = 1; i < length; i++) {
                if (prices[i] < prices[i-1]) {
                    result+=prices[i-1]-prices[in];
                    in = i;
                }
            }
            result+=prices[length-1]-prices[in];
        }
        return result;
    }
}
image

官方解

https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-ii/solution/mai-mai-gu-piao-de-zui-jia-shi-ji-ii-by-leetcode-s/

  1. 动态规划

    i天的收益就看第i-1天是否持有,通过这样的关系列出动态方程,写出代码

    class Solution {
        public int maxProfit(int[] prices) {
            int n = prices.length;
            int[][] dp = new int[n][2];
            dp[0][0] = 0;
            dp[0][1] = -prices[0];
            for (int i = 1; i < n; ++i) {
                dp[i][0] = Math.max(dp[i - 1][0], dp[i - 1][1] + prices[i]);
                dp[i][1] = Math.max(dp[i - 1][1], dp[i - 1][0] - prices[i]);
            }
            return dp[n - 1][0];
        }
    }
    

    虽然看起来麻烦了些,但是是使用动态规划解决的好例子

    • 时间复杂度:O(n)
    • 空间复杂度:O(1)
  2. 贪心

    类似于我的处理,但计算了每个价格的区间,去掉负数

    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;
        }
    }
    
    • 时间复杂度:O(n)
    • 空间复杂度:O(1)

相关文章

网友评论

    本文标题:Day60 买卖股票的最佳时机II

    本文链接:https://www.haomeiwen.com/subject/xbsmhltx.html