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

      

  • 相关阅读:
    springCloud 服务间相互调用
    不同环境下整合相同格式的文件
    Linux 安装mysql
    利用Maven打War包引入本地Jar包
    linux服务器部署项目详细步骤
    DM数据库导入dmp文件报大小写敏感问题解决办法
    synchronized 实现过程
    TypeScript学习笔记
    @RequestMapping注解详解
    常用的Linux命令
  • 原文地址:https://www.cnblogs.com/averillzheng/p/3771656.html
Copyright © 2011-2022 走看看