Maximum Subarray Problem: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
Line 46: Line 46:


=Divide-and-Conquer=
=Divide-and-Conquer=
To implement divide-and-conquer, we use the following idea: the profit for a day is given by the difference between the current price and the price in the previous day. As day pass, the overall profit is given by the sum of the differences described previously. The maximum profit is indicated by the contiguous subarray whose sum of elements returns the maximum possible value.


=O(n) Iterative Solution=
=O(n) Iterative Solution=

Revision as of 22:31, 9 August 2018

External

Internal

Overview

The maximum subarray problem is useful to solve the following problem: assuming we have access to stock prices of a company for a number of days, and the price does not change during a day, determine what would have been the best day to buy and the best day to sell one unit of stock to make the maximum profit, for the entire interval we have data for. For example, if we maintain the stock prices in an array, for 4 days (0-3) as follows {10, 8, 12, 11} then we would have made the biggest profit of 4 by buying on day 1 at 8 and selling on day 2 at 12.

The problem has an obvious O(n2) brute force approach solution, an O(?) divide-and-conquer solution and an O(n) iterative solution.

O(n2) Brute Force Approach

The stock prices are maintained in an int[n] array with an array element for each of the n days. We loop over the prices, and then in an inner loop we calculate the difference in price between subsequent days and the current day, maintaining the maximum.

public void bruteForce(int[] price) {

  int maxProfit = Integer.MIN_VALUE;
  int buy = -1; // the index of the day we should buy
  int sell = -1; // the index of the day we should sell

  for(int i = 0; i < price.length; i ++) {

    for(int j = i + 1; j < price.length; j ++) {

      // we only compare with price in subsequent days
      int profit = price[j] - price[i];

      if (profit > maxProfit) {
        maxProfit = profit;
        buy = i;
        sell = j;
      }
    }
  }
}

Working code:

Playground MaxProfit.bruteForce()

The time complexity is given by the following sum: (n-1) + (n-2) + ... + 1, which is O(n2).

Divide-and-Conquer

To implement divide-and-conquer, we use the following idea: the profit for a day is given by the difference between the current price and the price in the previous day. As day pass, the overall profit is given by the sum of the differences described previously. The maximum profit is indicated by the contiguous subarray whose sum of elements returns the maximum possible value.

O(n) Iterative Solution

Playground

https://github.com/NovaOrdis/playground/tree/master/data-structures-and-algorithms/maximum-subarray-problem