1. 程式人生 > >股市的交易日(動態規劃演算法)

股市的交易日(動態規劃演算法)

股市的交易日


///
/// 在股市的交易日中,假設最多可進行兩次買賣(即買和賣的次數均小於等於2),規則是必須一筆成交後進行另一筆(即買-賣-買-賣的順序進行)。給出一天中的股票變化序列,請寫一個程式計算一天可以獲得的最大收益。
///給定價格序列prices及它的長度n,請返回最大收益。保證長度小於等於500。
///測試樣例:
///[10,22,5,75,65,80],6
///返回:
///87
///

想法:

最多兩次交易,前一次交易與後一次交易的結果想加,有關聯,所以選用 動態規劃演算法

把序列分為兩段

10 ||22 5 75 65 80
10 22||5 75 65 80
10 22 5||75 65 80

計算前一段跟後一段的最優解相加最優

c# 程式碼1

///使用: 
/// int[] prices = { 10,2,5,75,65,80,5,6 };
/// int max = maxProfit2(prices, prices.Length);
///方法:
 static int maxProfit2(int[] prices, int n)
        {
            Console.WriteLine("maxProfit2");
            int times = 0;
            int max = 0;
            int onemax = 0, twomax = 0;
            for
(int i = 0; i < n; i++) { onemax = 0; twomax = 0; for (int j2 = 0; j2 < i; j2++) { for (int j3 = j2; j3 < i; j3++) { times++; int vTmp = prices[j3] - prices[j2]; if
(vTmp > onemax) { onemax = vTmp; } } } for (int k2 = i; k2 < n; k2++) { for (int k3 = k2; k3 < n; k3++) { times++; int vTmp = prices[k3] - prices[k2]; if (vTmp > twomax) { twomax = vTmp; } } } Console.WriteLine(onemax + "--"+ twomax); int tmpMax = onemax + twomax; if (max < tmpMax) { max = tmpMax; } } Console.WriteLine("maxProfit2-end:" + times); return max; }

c# 程式碼2

///使用: 
/// int[] prices = { 10,2,5,75,65,80,5,6 };
/// int max = maxProfit3(prices, prices.Length);
///方法:
static int maxProfit3(int[] prices, int n) 
        {
            Console.WriteLine("maxProfit3");
            int max = 0;
            int times = 0;
            int onemax, twomax;
            for (int i = 0; i < n; i++)
            {
                onemax = 0; twomax = 0;
                for (int j = 0; j < i; j++)
                {
                    for (int j2 = 0; j2 < j; j2++)
                    {
                        times++;
                        int tmpPri = prices[j] - prices[j2];
                        if (tmpPri > onemax)
                        {
                            onemax = tmpPri;
                        }
                    }

                }
                for (int k = i + 1; k < n; k++)
                {
                    times++;
                    if ((prices[k] - prices[i]) > twomax)
                    {
                        twomax = prices[k] - prices[i];
                    }
                }
                Console.WriteLine(onemax + "--" + twomax);
                int tmpMax = onemax + twomax;
                if (tmpMax > max)
                {
                    max = tmpMax;
                }
            }
            Console.WriteLine("maxProfit3-end:" + times);
            return max;
        }