zoukankan      html  css  js  c++  java
  • [LeetCOde][Java] Best Time to Buy and Sell Stock III

    题目:

    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).

    算法分析:

    利用通用的算法《Best Time to Buy and Sell Stock IV》 将k变为2 就ok 

    AC代码:

    <span style="font-family:Microsoft YaHei;font-size:12px;">public class Solution
    {
        public int maxProfit(int[] prices) 
        {
            return maxProfit(2,prices);
        }
        public int maxProfit(int k, int[] prices) 
        {
           if(prices==null || prices.length==0)
                return 0;
            if(k>prices.length)//k次数大于天数时,转化为问题《Best Time to Buy and Sell Stock II》--无限次交易的情景 
            {
                if(prices==null)
                    return 0;
                int res=0;
                for(int i=0;i<prices.length-1;i++)
                {
                    int degit=prices[i+1]-prices[i];
                    if(degit>0)
                        res+=degit;
                }
                return res;
            }
            /*
          定义维护量:
          global[i][j]:在到达第i天时最多可进行j次交易的最大利润。此为全局最优
          local[i][j]:在到达第i天时最多可进行j次交易而且最后一次交易在最后一天卖出的最大利润。此为局部最优
          定义递推式:
          global[i][j]=max(global[i-1][j],local[i][j]);即第i天没有交易,和第i天有交易
          local[i][j]=max(global[i-1][j-1]+max(diff,0),local[i-1][j]+diff)  diff=price[i]-price[i-1];
           */
            int[][] global=new int[prices.length][k+1];
            int[][] local=new int[prices.length][k+1];
            for(int i=0;i<prices.length-1;i++)
            {
                int diff=prices[i+1]-prices[i];
                for(int j=0;j<=k-1;j++)
                {
                    local[i+1][j+1]=Math.max(global[i][j]+Math.max(diff,0),local[i][j+1]+diff);
                    global[i+1][j+1]=Math.max(global[i][j+1],local[i+1][j+1]);
                }
            }
            return global[prices.length-1][k];
        }
    }</span>

  • 相关阅读:
    [SCOI2009] Windy数
    [P1361] 小M的作物
    Wannafly Camp 2020 Day 2E 阔力梯的树
    2017百越杯反序列化writeup
    大美西安writeup
    Thinkphp的SQL查询方式
    Thinkphp的CURD
    记一次拿webshell踩过的坑(如何用PHP编写一个不包含数字和字母的后门)
    ThinkPHP的输出和模型使用
    ThinkPHP的运行流程-2
  • 原文地址:https://www.cnblogs.com/jhcelue/p/6938158.html
Copyright © 2011-2022 走看看