zoukankan      html  css  js  c++  java
  • 0122. Best Time to Buy and Sell Stock II (E)

    Best Time to Buy and Sell Stock II (E)

    题目

    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

    题意

    在一个时刻买入股票,在另一个时刻卖出股票,可以多次交易,求能得到的最大收益。

    思路

    动态规划:0309. Best Time to Buy and Sell Stock with Cooldown (M) 方法一样。

    One Pass:从左到右遍历数组,只要后一天的价格比前一天高,那么就可以把这份利润加入到总利润中。但这并不是说可以卖出后又在同一天买入,例如:[1, 2, 3],按照我们的方法看起来像是 1买入->2卖出->2买入->3卖出,实际上的交易只有 1买入->3卖出,中间的部分只是数学意义上的变通。


    代码实现

    Java

    动态规划

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

    One Pass

    class Solution {
        public int maxProfit(int[] prices) {
            int sum = 0;
            for (int i = 0; i < prices.length - 1; i++) {
                sum += prices[i + 1] > prices[i] ? prices[i + 1] - prices[i] : 0;
            }
            return sum;
        }
    }
    
  • 相关阅读:
    用 SuperObject 解析淘宝上的 Json 数据
    JSON 之 SuperObject(17): 实例
    JSON 之 SuperObject(16): 实例
    JSON 之 SuperObject(15): 实例
    JSON 之 SuperObject(14): 从 XML 中解析
    JSON 之 SuperObject(13): 关于 SO 与 SA 函数
    JSON 之 SuperObject(12): TSuperEnumerator、TSuperAvlIterator、ObjectFindFirst...
    IO 流
    Servlet的创建和生命周期
    分页
  • 原文地址:https://www.cnblogs.com/mapoos/p/13516614.html
Copyright © 2011-2022 走看看