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;
        }
  • 相关阅读:
    在java中写出完美的单例模式
    Zookeeper的功能以及工作原理
    java面试题之int和Integer的区别
    ActiveMQ面试专题
    并发队列ConcurrentLinkedQueue、阻塞队列AraayBlockingQueue、阻塞队列LinkedBlockingQueue 区别和使用场景总结
    Python requests 指定网卡ip发出请求
    Python 打包发布exe可执行文件
    Power BI 图标设置
    python git 基础操作
    C#通过SFTP协议操作文件
  • 原文地址:https://www.cnblogs.com/lasclocker/p/4997524.html
Copyright © 2011-2022 走看看