买入和卖出股票,时间复杂度为O(n log n)

时间:2015-07-04 07:55:18

标签: java divide-and-conquer

编辑:
我很感谢你们两个人的帮助,但我必须坚持使用O(n log n)时间竞争力,并且必须使用二进制递归的分而治之技术。我在最初的帖子中没有说清楚

我有一个未分类的整数,我必须在第i天购买股票并在第j天卖出以获得最大利润,其中第i个(较小的值)日必须在第j个之前(较大的值) ) 天。到目前为止,我已经找到了一个返回购买和销售天数(数组的索引值)和最大利润的解决方案,但它有一个O(n ^ 2)时间复杂度,我很难到达O(n记录时间复杂性并实施分而治之

public static Profit BestProfit( int[] a, int i, int j )
{
   Profit bestProfit = new Profit();

   int n = j; 
   int maxProfit = 0;
   for(i = 0; i < n; i++)
   {
      for(j = i; j < n; j++)
      {
         if(a[j] - a[i] > maxProfit)
         {
            maxProfit = a[j] - a[i];
            bestProfit.setBuy( i );
            bestProfit.setSell( j );
            bestProfit.setMaxProfit( maxProfit );
         }
      }
   return bestProfit;
   } 

params i是数组的开头,j是数组末尾的 Profit类是我创建的用于保持买入,卖出和获利价值的类。

我发现需要考虑的三个案例是阵列上半部分的最大利润,阵列后半部分的最大利润,以及上半部分最小值的情况数组的最大值和最大值是在数组的后半部分(我已经用一个简单的最小/最大函数完成了这部分问题,解决了最后的情况)。

我很困惑,任何帮助分裂和征服实施或技巧提示将不胜感激!

3 个答案:

答案 0 :(得分:1)

在O(n)中,非常简单:

public static Profit bestProfit(int[] a, int begin, int end) {
    Profit bestProfit = new Profit();
    int min = a[begin];
    int max = a[begin];
    int index = begin;
    int buy = 0;
    int sell = 0;
    int minIndex = begin;
    int maxIndex;
    int maxProfit = 0;
    for (int i = begin; i < end; i++) {
        int n = a[i];
        if (n < min) {
            minIndex = index;
            min = n;
            max = n;
        } else if (max < n) {
            max = n;
            maxIndex = index;
            if (maxProfit < (max - min)) {
                maxProfit = max - min;
                buy = minIndex;
                sell = maxIndex;
            }
        }
        index++;
    }
    bestProfit.setBuy(buy);
    bestProfit.setSell(sell);
    bestProfit.setMaxProfit(maxProfit);
    return bestProfit;
}

编辑:分而治之:

public static int divideAndConquer(int[] a, int i, int j, Profit profit, int min) {
    int minResult;
    if (i+1 >= j) {
        minResult = Math.min(a[i], min);
        if (a[i] - min > profit.getMaxProfit()) {
            profit.setBuy(min);
            profit.setSell(a[i]);
            profit.setMaxProfit(a[i] - min);
        }
    } else {
        int n = (j+i)/2;
        minResult = divideAndConquer(a, i, n, profit, min);
        minResult = divideAndConquer(a, n, j, profit, minResult);
    }
    return minResult;
}

public static void main(String[] args) {
    int[] prices = {20, 31, 5, 7, 3, 4, 5, 6, 4, 0, 8, 7, 7, 4, 1,10};
    Profit profit =new Profit();
    divideAndConquer(prices, 0, prices.length, profit, Integer.MAX_VALUE);
    System.out.println(profit);
}

答案 1 :(得分:1)

只需三个循环即可将其改进为O(n):

  • 构建最小数组的第一个循环
  • 构建最大数组的第二个循环
  • 找到最大利润的第三个循环

或多或少:

public static void main(String[] args) {

    int[] stockPrices = {2, 9, 5, 7, 3, 4, 5, 6, 4, 0, 8, 7, 7, 4, 1};

    int[] mins = new int[stockPrices.length - 1];
    int[] minsIndex = new int[stockPrices.length - 1];
    int[] maxs = new int[stockPrices.length - 1];
    int[] maxsIndex = new int[stockPrices.length - 1];

    int minIndex = -1;
    int min = Integer.MAX_VALUE;
    for (int i = 0; i < stockPrices.length - 1; i++) {
        if (stockPrices[i] < min) {
            min = stockPrices[i];
            minIndex = i;
        }
        mins[i] = min;
        minsIndex[i] = minIndex;
    }

    System.out.println("mins idx: " + Arrays.toString(minsIndex));
    System.out.println("mins: " + Arrays.toString(mins));

    int maxIndex = -1;
    int max = -1;
    for (int i = stockPrices.length - 1; i > 0; i--) {
        if (stockPrices[i] > max) {
            max = stockPrices[i];
            maxIndex = i;
        }
        maxs[i - 1] = max;
        maxsIndex[i - 1] = maxIndex;
    }

    System.out.println("maxs idx: " + Arrays.toString(maxsIndex));
    System.out.println("maxs: " + Arrays.toString(maxs));

    int maxProfit = -1;
    int buyIndex = -1;
    int sellIndex = -1;
    for (int i = 0; i < stockPrices.length - 1; i++) {
        int profit = maxs[i] - mins[i];
        if (profit > maxProfit) {
            maxProfit = profit;
            buyIndex = minsIndex[i];
            sellIndex = maxsIndex[i];
        }
    }

    System.out.println("buy at: " + buyIndex + " sell at: " + sellIndex + " profit: " + maxProfit);
}

答案 2 :(得分:1)

好吧,既然你表达了使用分而治之的需要,我会给出另一个答案。

假设股票价格在数组中定义:[p0,p1,...,pn]。

我们可以将这个问题分成这个定义中的子问题。

max profit = max(maxprofit([p0], [p1..pn]), maxprofit([p0..p1], [p2..pn]), ..., maxprofit([p0..pn-1], [pn]))

maxprofit的第一个参数是购买价格数组,第二个参数是销售价格。

查看第一个子问题

maxprofit([p0], [p1..pn])

我们可以更加分开这个:

maxprofit([p0], [p1..pn]) = max(maxprofit([p0], [p1]), maxprofit([p0],[p2..pn]))

我们可以解决max([p0], [p1]),因为它是利润= p1-p0的基本问题。现在我们保留结果,然后缓存。继续分解maxprofit(([p0], [p2..pn])并继续缓存所有解决方案。

查看第二个子问题

这是问题所在:

maxprofit([p0..p1], [p2..pn])

可以分解为:

maxprofit([p0..p1], [p2..pn]) = max(maxprofit([p0], [p2..pn]), maxprofit([p1], [p2..pn]))

有趣的是:您不必分解maxprofit([p0], [p2..pn]),因为在处理第一个子问题时,您已经在缓存中使用了它。因此,只需要分解第二个子问题。

我想在这一点上你已经到了这里。基本上你需要不断解决问题,直到遇到基本问题或问题已经缓存。

相关问题