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

        public int maxProfit(int[] prices) {
            if(prices == null || prices.length == 0)
                return 0;
            int[] result1 = new int[prices.length];//保存正序扫描的最大收益
            int[] result2 = new int[prices.length];//保存反序扫描的最大收益
            int min = prices[0], max = prices[0];
            int result = 0;
            for (int i = 1; i < prices.length; i++) {//正序扫描
                if (prices[i] > max) { // 实时计算并保存最大收益
                    max = prices[i];
                    if (max - min > result) {
                        result = max - min;
                    }
                } else if (prices[i] < min) { // 重新规定查找区域
                    min = prices[i];
                    max = prices[i];
                }
                result1[i] = result;
            }
            min = prices[prices.length-1]; max = prices[prices.length-1]; result = 0;
            for (int i = prices.length-2; i >= 0; i--) {//反序扫描
                if (prices[i] < min) { // 实时计算并保存最大收益
                    min = prices[i];
                    if (max - min > result) {
                        result = max - min;
                    }
                } else if (prices[i] > max) { // 重新规定查找区域
                    min = prices[i];
                    max = prices[i];
                }
                result2[i] = result;
            }
            int max_profit = 0;
            for (int i = 0; i < prices.length; i++) {//叠加求和,输出最大值
                if (result1[i] + result2[i] > max_profit) {
                    max_profit = result1[i] + result2[i];
                }
            }
            return max_profit;
        }
  • 相关阅读:
    Linux安装gitlab
    logback日志配置
    spring源码-aop动态代理-5.3
    【转】阿里云免费SSL证书申请与安装使用(IIS7)
    WebApi 全局使用filter
    Mint-UI Picker 三级联动
    P标签莫名有了margin-top值的原因
    Vue为v-html中标签添加CSS样式
    【转】C# string数组转int数组
    【转】SQLServer汉字转全拼音函数
  • 原文地址:https://www.cnblogs.com/lasclocker/p/4997524.html
Copyright © 2011-2022 走看看