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

    public class S123 {
        //分成两段求最大子数组,
        //forward[i]表示1~i这段最大子数组和,backward[i]表示从prices.length-1~1这段最大子数组和
        //最后找出forward[i]与backward[i+1]和最大值即所求
        //求forward[i]与backward[i]的方法与053kadane's algorithm类似
        public int maxProfit(int[] prices) {
            if(prices.length<2)
                return 0;
            int result =0;
            int sum = 0;
            int []forward = new int[prices.length];
            forward[0] = Integer.MIN_VALUE;
            int []backward = new int[prices.length+1];
            backward[prices.length] = Integer.MIN_VALUE;
            for(int i = prices.length-1;i>0;i--){
                prices[i] = prices[i]-prices[i-1];
                if(sum<0) sum = 0;
                sum+=prices[i];
                backward[i] = sum>backward[i+1]?sum:backward[i+1];
            }
            sum = 0;
            for(int i = 1;i<prices.length;i++){
                if(sum<0) sum = 0;
                sum+=prices[i];
                forward[i] = sum>forward[i-1]?sum:forward[i-1];
                if(forward[i]>0&&backward[i+1]>0){
                    result = forward[i]+backward[i+1]>result?forward[i]+backward[i+1]:result;
                }else{
                    result = forward[i]>result?forward[i]:result;
                    result = backward[i+1]>result?backward[i+1]:result;
                }
            }
            return result;
        }
    }
  • 相关阅读:
    【python接口自动化】httpUtils
    mac上安装chromedriver
    python自动化测试报告(excel篇)
    Fiddler 手机抓包介绍
    Fiddler 简单介绍
    Python splinter 环境搭建
    Python pip 常用命令
    Python Yaml 学习
    Jmeter
    Python3 操作Excel
  • 原文地址:https://www.cnblogs.com/fisherinbox/p/5291302.html
Copyright © 2011-2022 走看看