zoukankan      html  css  js  c++  java
  • Best Time to Buy and Sell Stock III 解答

    Question

    Say you have an array 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 at most two transactions.

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

    Solution

    This problem can be solved by "divide and conquer". We can use left[i] array to track maximum profit for transactions before i (including i), and right[i + 1] to track maximum profit for transcations after i.

    Prices: 1 4 5 7 6 3 2 9
    left = [0, 3, 4, 6, 6, 6, 6, 8]
    right= [8, 7, 7, 7, 7, 7, 7, 0]

     Time complexity O(n), space cost O(n).

     1 public class Solution {
     2     public int maxProfit(int[] prices) {
     3         if (prices == null || prices.length < 2)
     4             return 0;
     5         int length = prices.length, min = prices[0], max = prices[length - 1], tmpProfit = 0;
     6         int[] leftProfits = new int[length];
     7         leftProfits[0] = 0;
     8         int[] rightProfits = new int[length];
     9         rightProfits[length - 1] = 0;
    10         // Calculat left side profits
    11         for (int i = 1; i < length; i++) {
    12             if (prices[i] > min)
    13                 tmpProfit = Math.max(tmpProfit, prices[i] - min);
    14             else
    15                 min = prices[i];
    16             leftProfits[i] = tmpProfit;
    17         }
    18         // Calculate right side profits
    19         tmpProfit = 0;
    20         for (int j = length - 2; j >= 0; j--) {
    21             if (prices[j] < max)
    22                 tmpProfit = Math.max(tmpProfit, max - prices[j]);
    23             else
    24                 max = prices[j];
    25             rightProfits[j] = tmpProfit;
    26         }
    27         // Sum up
    28         int result = Integer.MIN_VALUE;
    29         for (int i = 0; i < length - 1; i++)
    30             result = Math.max(result, leftProfits[i] + rightProfits[i + 1]);
    31         result = Math.max(result, leftProfits[length - 1]);
    32         return result;
    33     }
    34 }
  • 相关阅读:
    Git分支合并:Merge、Rebase的选择
    linux系统下MySQL表名区分大小写问题
    Spring Mvc和Spring Boot读取Profile方式
    Git删除远程分支
    TortoiseGit push免输密码
    git [command line] fatal: Authentication failed for
    Jenkins [Error] at org.codehaus.cargo.container.tomcat.internal.AbstractTomcatManagerDeployer.redeploy(AbstractTomcatManagerDeployer.java:192)
    FAIL
    WIN下修改host文件并立即生效
    MYSQL 创建数据库SQL
  • 原文地址:https://www.cnblogs.com/ireneyanglan/p/4825130.html
Copyright © 2011-2022 走看看