zoukankan      html  css  js  c++  java
  • 123. 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).

    这道题要求我们最多做两笔交易,求其最大利润。此题是DP题目,需要写出状态方程,即profit = transaction(1)+transaction(2)=sell(1)-buy(1)+sell(2)-buy(2)。代码如下:

    public class Solution {

        public int maxProfit(int[] prices) {

            int buy1 = Integer.MIN_VALUE;

            int buy2 = Integer.MIN_VALUE;

            int sell1 = 0;

            int sell2 = 0;

            for(int i=0;i<prices.length;i++){

                buy1 = Math.max(buy1,-prices[i]);

                sell1 = Math.max(sell1,prices[i]+buy1);

                buy2 = Math.max(buy2,sell1-prices[i]);

                sell2 = Math.max(sell2,buy2+prices[i]);

            }

            return sell2;

        }

    }

  • 相关阅读:
    暑期实践
    noi前第十九场 题解
    noi前第十八场 题解
    noi前第十七场 题解
    noi前第十六场 题解
    noi前第十五场 题解
    noi前第十四场 题解
    noi前第十三场 题解
    [NOI2017]游戏「2-SAT」
    空间宝石「最短路+线段树」
  • 原文地址:https://www.cnblogs.com/codeskiller/p/6358634.html
Copyright © 2011-2022 走看看