0

I am now using divide and conquer algorithm to find maximum difference between two ordered elements(it means that A[i][j] − A[k][l] where k>i and l>j) in a two dimension array, like the below one:

[ 0, 3, 6, 4]

[ 9, 3, 1, 6]

[ 7, 8, 5, 6]

[ 1, 2, 3, 4]

So the result is A[1][2] − A[0][0] = 8 - 0 = 8 (not A[0][1] − A[0][0] = 9 - 0 = 9.

The most question are in a single dimensional array, like below question:

Divide and Conquer Algo to find maximum difference between two ordered elements

So how can I solve it in a two dimensional array by divide and conquer algorithm?

Thanks a lot!

Zeman
  • 63
  • 1
  • 4
  • Can you better explain the algorithm you used to arrive at `8 - 0 = 8` for the final answer? This is not clear to me. – Tim Biegeleisen Sep 29 '17 at 02:16
  • That's why I ask this question. I don't know how to use divide and conquer algorithm to get the final answer. – Zeman Sep 29 '17 at 02:43
  • I get it now, `8` is your current incorrect result. Are these arrays sorted in any way? – Tim Biegeleisen Sep 29 '17 at 02:44
  • I am sorry that the format I write may mislead you. The example I write is not 4 arrays, it is a 4*4 two-dimensional array. My question is for given n*n two-dimensional array A, how to find maximum A[i][j] − A[k][l] where k>i and l>j. – Zeman Sep 29 '17 at 03:08

1 Answers1

1

There is a straight O(n^2) solution. In order to calc max of A[i][j] − A[k][l], let's fix A[k][l] at the moment. Suppose A[k][l] = x in the following graph. Then the candidate set of A[i][j] is the shaded rectangle.

So in order to make A[i][j] − x maximum. We need to know the max value of the shaded area, this could be calc by simple dynamic programming.

+------+------+------+-----+
|      |      |      |     |
|      |      |      |     |
|      |      |      |     |
+--------------------------+
|      |      |      |     |
|      |  x   |      |     |
|      |      |      |     |
+--------------------------+
|      |      |------------|
|      |      |------------|
|      |      |------------|
+--------------------------|
|      |      |------------|
|      |      |------------|
|      |      |------------|
+------+-------------------+

Define

  • area(i, j) = { A[x][y] | x > i, y > j }
  • f(i, j) = max( area(i, j) )
  • g(m, n) = max { f(i, j) - A[i][j] | 1 <= i <= m, 1 <= j <= n }

Then for a m*n matrix, what we want is f(m, n).

And f(i, j) = max { f(i+1, j), f(i, j+1), A[i][j] }

So 2 for loops should do the work.

delta
  • 3,778
  • 15
  • 22