zoukankan      html  css  js  c++  java
  • LeetCode -- Best Time to Buy and Sell Stock III

    Question:

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

    Analysis:

    问题描述:给出一个整数数组,其中第i个元素表示第i天得股价。

    设计一个程序找到最大利润,最多只能进行两次交易。

    思路一:暴力求解方法。一次循环分成两段,每段求最大利润,然后找到最大利润,时间复杂度为O(n2).

    思路二:Dynamic Programming的思想。首先正向遍历一遍,计算若是当前交易能够得到的profit;然后逆向遍历一遍(正向遍历与逆向遍历要求的东西是不一样的,正向是求当前如果进行交易的话能够得到的profit,而逆向遍历要求从i到最后能够获得的最大收益)。

    Answer:

    public class Solution {
     public static int maxProfit(int[] prices) {
                if(prices.length == 0 || prices.length == 1)
                    return 0;
            
                int n = prices.length;
                
                //正向寻找最大利润
                int low = prices[0];
                int profit0 = 0;
                int [] pro = new int[n];
                pro[0] = 0;
                for(int i=1; i<n; i++) {
                    if(prices[i] < low)
                        low = prices[i];
                    int temp = prices[i] - low;
                    if(profit0 < temp)
                        profit0 = temp;
                    pro[i] = temp;
                }
                
                //逆向寻找最大利润
                int high = prices[prices.length - 1];
                int profit1 = 0;
                int[] pro1 = new int[n];
                pro1[n-1] = 0;
                for(int i=n - 2; i>=0; i--) {
                    if(high < prices[i])
                        high = prices[i];
                    int temp = high - prices[i];
                    if(profit1 < temp) 
                        profit1 = temp;
                    pro1[i] = profit1;
                }
                
                int res = 0;
                for(int i=0; i<n; i++) {
                    int temp = pro[i] + pro1[i];
                    //System.out.println("pro: "+pro[i]+" pro1: "+pro1[i] );
                    if(res < temp)
                        res = temp;
                }
                
            return res;
        }
     
        
    }
  • 相关阅读:
    Codeforces Round #359 (Div. 2) C. Robbers' watch 鸽巢+stl
    poj 3616 Milking Time dp
    UVA 11401
    UVA 11806 Cheerleaders dp+容斥
    Educational Codeforces Round 4 D. The Union of k-Segments 排序
    Codeforces Round #337 (Div. 2) C. Harmony Analysis 数学
    Codeforces Round #337 (Div. 2) B. Vika and Squares 水题
    Codeforces Round #337 (Div. 2) A. Pasha and Stick 水题
    POJ2402/UVA 12050 Palindrome Numbers 数学思维
    UVA 11076 Add Again 计算对答案的贡献+组合数学
  • 原文地址:https://www.cnblogs.com/little-YTMM/p/4821658.html
Copyright © 2011-2022 走看看