Best Time to Buy and Sell Stock I && II && III

來源:互聯網
上載者:User

題目1:Best Time to Buy and Sell Stock

Say you have an array for which the ith element is the price of a given stock on day i.

If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.

分析:題意給我們一個數組prices[], 用來表示股票每一天的價格,問我們如果“只多進行一次交易”(即買進之後再賣出), 應該在哪天買進,哪天賣出所獲得的利潤能達到最大值。如:prices={1, 3, 4, 10, 1};那麼最大的利潤是第一天買進(價格為1),然後第四天賣出(價格為10), 利潤最大為9
明白了題意之後,我們來看看能怎樣解決這道題目。由於是只能交易一次,而且必須先有“買進”,才能有“賣出”因此我們只需要數組的最後一位往前掃描,依次得到哪一天的prices是最大的(設為maxPrices),然後在算出和這一天前面的某一天prices[i]的差值 (maxPrices - prices[i]),如果大於最大的利潤值,則更新最大利潤值maxMoney;
AC代碼: 
public class Solution {        public int maxProfit(int[] prices) {        int size = prices.length;        if (size == 0){            return 0;        }        int maxPrice = prices[size-1];//初始化最大price        int maxMoney = 0;//初始化利潤值        for (int i=size-1; i>=0; --i){            maxPrice = maxPrice > prices[i] ? maxPrice : prices[i];//如果第i天的值大於最大price,則更新最大price的值            maxMoney = maxMoney > (maxPrice - prices[i]) ? maxMoney : (maxPrice - prices[i]);//更新最大利潤值        }        return maxMoney;    }}

題目2:Best Time to Buy and Sell Stock II

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 as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).


分析:
這道題目,關鍵是要理解題意,題意中和題目I是有點像,唯一不同的是這道題目可以進行多次交易,但是要注意的是,每次最多隻能持有一支股票在手上,也就是說你要再買入的時候,必須先把手頭上的這股票先賣掉!舉個例子:如Prices[] = {1,3,4,10,2};這樣子的話,你可以採取的方式有1、第1天買入(price==1),第2天賣出(price==3), 第3天買入(price==4),第4天賣出(price==10)  :   82、第1天買入(price==1),第3天賣出(price==4)       : 33、第2天買入(price==3),第3天賣出(price==4)       : 14、第3天買入(price==4),第4天賣出(price==10)     : 65、第1天買入(price==1),第4天賣出(price==10)     : 9但其實如果仔細觀察容易發現 : 3 - 1 = 24 - 3 = 110 - 4 = 6
然後result = 2 + 1 + 6 = 9因此其實我們只是要找增長的序列對,並求出他們的差值的和index :  1 ~~ prices.size()-1通過這樣分析的話,我們很容易知道其實只要從頭到尾遍曆,如果 prices[index] > prices[index-1] 
AC代碼:
public class Solution {    public int maxProfit(int[] prices) {        int profit = 0;        int size = prices.length;        if (size < 2){            return profit;        }        for (int index=1; index<size; ++index){            int value = prices[index] - prices[index-1];            if (value > 0){                profit += value;            }        }        return profit;    }}


題目3: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).

分析:由於最多隻可以進行兩次交易,而且兩次交易之間必須沒有交集。這題用DP來做.那我們很容易想到,將數組劃分成兩塊,左邊一塊 | 右邊一塊,我們只需要求出左邊的最大利潤,再求出右邊的最大利潤,然後相加起來就得到了利潤的最大值我們用用left[i] 來表示[0,...,i]中的最大利潤
用right[i]來表示[i,...,n-1]上的最大利潤
AC代碼:
public class Solution {    public int maxProfit(int[] prices) {        int size = prices.length;        if (size < 2)            return 0;        int[] left = new int[size];        int[] right = new int[size];        int minValue = prices[0];        int maxValue = prices[size-1];        for (int i=1; i<size; ++i){            left[i] = left[i-1] > (prices[i] - minValue) ? left[i-1] : (prices[i] - minValue);            minValue = minValue < prices[i] ? minValue : prices[i];        }        for (int i=size-2; i>=0; --i){            right[i] = right[i+1] > (maxValue - prices[i]) ? right[i+1] : (maxValue - prices[i]);            maxValue = maxValue > prices[i] ? maxValue : prices[i];        }        int profit=0;        for (int i=0; i<size; ++i){            profit = profit > (left[i] + right[i]) ? profit : (left[i] + right[i]);        }        return profit;    }}


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.