• 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;

        }

    }

  • 相关阅读:
    mac允许安装任何来源的软件
    Xcode Edit Schemes
    认识下算法工程师
    一定要熟练地使用常用的Foundation服务
    常用的UI控件
    认识iOS系统架构
    深拷贝/浅拷贝的理解
    Create Fiori List App Report with ABAP CDS view – PART 1
    [転載]SAP S/4HANAトライアル環境でCDS Viewを確認
    ABAP CDS
  • 原文地址:https://www.cnblogs.com/codeskiller/p/6358634.html
Copyright © 2020-2023  润新知