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).

    public class Solution {
        /**
    	 * To solve this problem, we use two array to save the max profit.
    	 * The running time is O(n)
    	 * 
    	 * @param prices --input price array
    	 * @return maximum profit 
    	 * @author Averill Zheng
    	 * @version 2014-06-04
    	 * @since JDK 1.7
    	 */
    	public int maxProfit(int[] prices) {
    		int maxProfit = 0;
    		int length = prices.length;
    		if(length > 0){
    			//maximum in order
    			int[] maxInOrder = new int[length];
    			maxInOrder[0] = 0; 
    			int min = prices[0];
    			for(int i = 1; i < length; ++i){
    				if(prices[i] - min >= maxInOrder[i - 1])
    					maxInOrder[i] = prices[i] - min;
    				else
    					maxInOrder[i] = maxInOrder[i - 1];
    				min = (prices[i] < min) ? prices[i] : min;
    			}
    			//maximum in reverse order
    			int[] maxInReverseOrder = new int[length];
    			maxInReverseOrder[length - 1] =0;
    			int max = prices[length - 1];
    			for(int i = length -2; i > -1; --i){
    				if(max - prices[i] > maxInReverseOrder[i + 1])
    					maxInReverseOrder[i] = max - prices[i];
    				else
    					maxInReverseOrder[i] = maxInReverseOrder[i + 1];
    				max = (prices[i] > max) ? prices[i] : max;
    			}
    			//find the maxProfit 
    			for(int k = 0; k < length; ++k)
    				maxProfit = (maxProfit < maxInOrder[k] + maxInReverseOrder[k]) ? maxInOrder[k] + maxInReverseOrder[k] : maxProfit;
    		}
    		return maxProfit;
        }  
    }
    

      

  • 相关阅读:
    2003开机自动登陆然后马上锁定计算机
    修改DNS、网关的VBS代码,不需重起即时生效
    页面自动刷新代码
    dos命令给权限
    无法运行VBS代码
    去掉2003或2kserver版的系统启动报错
    让易语言的信息框总在最前
    教你轻松搞定RJ45网线接头
    小技巧:如何设定永久通用WinRAR压缩密码
    Bootstrap入门教程
  • 原文地址:https://www.cnblogs.com/averillzheng/p/3771656.html
Copyright © 2011-2022 走看看