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

      

  • 相关阅读:
    图论算法——最短路系列
    1126 数字统计 2010年NOIP全国联赛普及组
    JavaEE Tutorials (10)
    情书
    洛谷 P1171 售货员的难题
    洛谷 P1769 淘汰赛制_NOI导刊2010提高(01)
    洛谷 P1858 多人背包
    HDU 2639 Bone Collector II
    国庆 day 6 下午
    国庆 day 6 上午
  • 原文地址:https://www.cnblogs.com/averillzheng/p/3771656.html
Copyright © 2011-2022 走看看