## Maximum Difference In An Array

### April 1, 2011

Today’s problem is this:

Given an array

X, find thejandithat maximizesX−_{j}X, subject to the condition that_{i}i≤j. If two differenti,jpairs have equal differences, choose the “leftmost shortest” pair with the smallestiand, in case of a tie, the smallestj.

For instance, given an array [4, 3, 9, 1, 8, 2, 6, 7, 5], the maximum difference is 7 when *i*=3 and j=*4*. Given the array [4, 2, 9, 1, 8, 3, 6, 7, 5], the maximum difference of 7 appears at two points, but by the leftmost-shortest rule the desired result is *i*=1 and *j*=2. *I* and *j* need not be adjacent, as in the array [4, 3, 9, 1, 2, 6, 7, 8, 5], where the maximum difference of 7 is achieved when *i*=3 and *j*=7. If the array is monotonically decreasing the maximum difference is 0, which by the leftmost-shortest rule occurs when *i*=0 and *j*=0.

There are at least two solutions. The obvious solution that runs in quadratic time uses two nested loops, the outer loop over *i* from 0 to the length of the array *n* and the inner loop over *j* from *i*+1 to *n*, computing the difference between *X _{i}* and

*X*and saving the result whenever a new maximum difference is found. There is also a clever linear-time solution that traverses the array once, simultaneously searching for a new minimum value and a new maximum difference; you’ll get it if you think about it for a minute.

_{j}Your task is to write both the quadratic and linear functions to compute the maximum difference in an array, and also a test function that demonstrates they are correct. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.

Pages: 1 2

My Haskell solution (see http://bonsaicode.wordpress.com/2011/04/01/programming-praxis-maximum-difference-in-an-array/ for a version with comments):

[…] today’s Programming Praxis exercise, our goal is to find the maximum difference between two numbers in a […]

I am having problem understanding of maximum difference in the above context.

In array [4, 3, 9, 1, 8, 2, 6, 7, 5] how come max diff is 7 instead of 8 i.e 9-1 = 8

and indices 2 <= 3 .

Sorry if it is dumb question :D

Cheers

Veer: The task is to maximize Xj – Xi, subject to i <= j. That means the scan has to go from left to right.

Thanks for clearing the doubt , I mistakenly read Xj – Xi as Xi – Xj .

Sorry, solution is quite big (I am new to this site – are there any posting limits?).

My idea is to scan array from left to right and maintain two variable max and min. Min is the minimum element found so far, and max is maximum element found after min. Also then one of these changes, calculate difference and check if it is bigger than previous one. Everything seems to work :)

Instead of (result1 == result2) should be (result1 != result2) :D

Additional idea – there is no need to save max. Instead of that simple check (anArray[i] – nSmallest). If (anArray[i] < nSmallest) then difference is negative number which is obliviously less than 0 (initial maximum). And if this difference is less than current maximum we can ignore it.

@arturasi How does your

`fnLinear`

handle the monotonicallydecreasing case, e.g.

`[5, 4, 3, 2, 1]`

?@arturasl Sorry! I read the letter at the end of your name as an “i” instead of

an “l.” Might need new glasses…

I have to say I needed help finding the linear solution; brain’s a bit slow on

Fridays I suppose. I’ve posted my solution on

github.

My code at http://codepad.org/VQAhDhfV

@Graham, I don’t mind :) Probably I had to use capital L :D

My fnLinear handles decreasing case correctly, because every time I change min value (which happens on every number in decreasing sequence) I also change max to min (because index of max number should be less or equal to min) which makes my procedure to check if maximum difference so far < 0. Which is always false as maximum difference so far is initialized to 0 by default. And so I get nSmallestPos = nLargestPos = nMax = 0.

Any way as I said before all this can be simplified to github

Which looks pretty much the same as your solution (taking into account my bad python skills :D )

Here’s a SQL version.

This propblem is analogous to maximum subsequence sum problem.

My try in REXX

#include

#include

int findMaxDiff(int *a, int size)

{

std::vector<std::pair > minmax(size);

int min = a[0];

int max = a[size – 1];

for(int i = 0; i < size; i++)

{

if(a[i] max)

max = a[size – 1 – i];

minmax[i].first = min;

minmax[size – 1 – i].second = max;

}

int maxDiff = minmax[0].second – minmax[0].first;

for(int i = 1; i maxDiff)

maxDiff = minmax[i].second – minmax[i].first;

}

return maxDiff;

}

int main()

{

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

std::cout << findMaxDiff(a, sizeof(a)/sizeof(int)) << std::endl;

return 0;

}

In F#,

I am trying to embed code through gist, but it’s not displayed. I just paste the raw text here.

(define (enumerate-interval low high)

(if (> low high)

‘()

(cons low (enumerate-interval (+ low 1) high))))

(define (accumulate op initial sequence)

(if (null? sequence)

initial

(op (car sequence)

(accumulate op initial (cdr sequence)))))

(define (last-index l)

(- (length l) 1))

(define (get-diff data j i)

(- (list-ref data j) (list-ref data i)))

(define (get-value result)

(car result))

(define (get-i result)

(cadr result))

(define (get-j result)

(caddr result))

(define (max-diff-internal max data)

(cond ((null? data) max)

((< (get-value max) (get-value (car data)))

(max-diff-internal (car data) (cdr data)))

((= (get-value max) (get-value (car data)))

(cond (( (get-i max) (get-i (car data)))

(max-diff-internal (car data) (cdr data)))

(else

(cond ((< (get-j max) (get-j (car data)))

(max-diff-internal max (cdr data)))

(else

(max-diff-internal (car data) (cdr data)))))))

(else

(max-diff-internal max (cdr data)))))

(define (max-diff data)

(let ((diff-result (accumulate append

'()

(map (lambda (i)

(map (lambda (j) (list (get-diff data j i) i j))

(enumerate-interval i (last-index data))))

(enumerate-interval 0 (last-index data))))))

(max-diff-internal (car diff-result) diff-result)))

(max-diff (list 4 3 9 1 8 2 6 7 5))

;linear-time solution

;result is a list contains (max-diff-value i j)

(define (max-diff-iter k min-i result data)

(cond ((= k (length data)) result)

(else

(let* ((new-min-i (if ( diff (get-value result))

(list diff new-min-i k)

result)))

(max-diff-iter (+ k 1) new-min-i new-result data)))))

(define (max-diff-test)

(assert (max-diff (list 4 3 9 1 8 2 6 7 5)) (list 7 3 4))

(assert (max-diff (list 4 2 9 1 8 3 6 7 5)) (list 7 1 2))

(assert (max-diff (list 4 3 9 1 2 6 7 8 5)) (list 7 3 7))

(assert (max-diff (list 5 4 3)) (list 0 0 0))

(assert (max-diff (list 1 3 3)) (list 2 0 1))

(assert (max-diff-iter 0 0 (list 0 0 0) (list 4 3 9 1 8 2 6 7 5)) (list 7 3 4))

(assert (max-diff-iter 0 0 (list 0 0 0) (list 4 2 9 1 8 3 6 7 5)) (list 7 1 2))

(assert (max-diff-iter 0 0 (list 0 0 0) (list 4 3 9 1 2 6 7 8 5)) (list 7 3 7))

(assert (max-diff-iter 0 0 (list 0 0 0) (list 5 4 3)) (list 0 0 0))

(assert (max-diff-iter 0 0 (list 0 0 0) (list 1 3 3)) (list 2 0 1)))

(max-diff-test)

This is the formatted one, please ignore or delete my previous comment

praxis.ss

[…] similar problem: find the maximum difference of two numbers in an array max difference […]

Javascript solution: