当前位置 : 首页 » 文章分类 :  算法  »  LeetCode.122.Best Time to Buy and Sell Stock II 买卖股票的最佳时机2

LeetCode.122.Best Time to Buy and Sell Stock II 买卖股票的最佳时机2

题目描述

122 Best Time to Buy and Sell Stock II
https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-ii/

Say you have an array prices for which the ith element is the price of a given stock on day i.

Design an algorithm to find the maximum profit. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times).

Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again).

Example 1:

Input: [7,1,5,3,6,4]
Output: 7
Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4.
             Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3.

Example 2:

Input: [1,2,3,4,5]
Output: 4
Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.
             Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are
             engaging multiple transactions at the same time. You must sell before buying again.

Example 3:

Input: [7,6,4,3,1]
Output: 0
Explanation: In this case, no transaction is done, i.e. max profit = 0.

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


解题过程

min 记录上次卖出之后的最小值,当价格上升时,继续持有不卖出。一旦遇到价格下降,则用昨天的最高值减去 min 卖出。

时间复杂度 O(n),空间复杂度 O(1)

private static class SolutionV2020 {
    public int maxProfit(int[] prices) {
        if (null == prices || prices.length < 2) {
            return 0;
        }
        int minIndex = 0;
        int maxProfit = 0;
        for (int i = 1; i < prices.length; i++) {
            if (prices[i] < prices[i - 1] && prices[i - 1] > prices[minIndex]) {
                // 价格开始下降,卖出
                maxProfit += prices[i - 1] - prices[minIndex];
                minIndex = i;
                continue;
            }
            minIndex = prices[i] < prices[minIndex] ? i : minIndex;
        }
        // 单独处理最后价格是上升的情况,最后卖出
        if (prices[prices.length - 1] > prices[minIndex]) {
            maxProfit += prices[prices.length - 1] - prices[minIndex];
        }
        return maxProfit;
    }
}

GitHub代码

algorithms/leetcode/leetcode/_122_BestTimeToBuyAndSellStock2.java
https://github.com/masikkk/algorithms/blob/master/leetcode/leetcode/_122_BestTimeToBuyAndSellStock2.java


上一篇 LeetCode.452.Minimum Number of Arrows to Burst Balloons 用最少数量的箭引爆气球

下一篇 LeetCode.011.Container With Most Water 盛最多水的容器

阅读
评论
434
阅读预计2分钟
创建日期 2020-04-19
修改日期 2020-04-19
类别

页面信息

location:
protocol:
host:
hostname:
origin:
pathname:
href:
document:
referrer:
navigator:
platform:
userAgent:

评论