## Maximum Difference In An Array

### April 1, 2011

We begin with the quadratic-time solution. Nested loops on *i* and *j* consider all possibilities, and variables *lo*, *hi* and *diff* are updated whenever a larger difference is found:

`(define (max-diff-quadratic xv)`

(define (x n) (vector-ref xv n))

(let ((len (vector-length xv)))

(let ((lo 0) (hi 0) (diff 0))

(do ((i 0 (+ i 1))) ((= i len) (list lo hi diff))

(do ((j (+ i 1) (+ j 1))) ((= j len))

(let ((d (- (x j) (x i))))

(when (< diff d)

(set! lo i) (set! hi j) (set! diff d))))))))

In the linear-time solution, *k* loops over the input vector, touching each element once. *Lo*, *hi* and *max-d* track the current maximum difference, *min-lo* tracks the minimum value seen so far, which may potentially be the site of a new lo if a corresponding hi with a difference greater than the current difference can be found. and *d* is the difference from *min-lo* at the current location:

`(define (max-diff-linear xv)`

(define (x n) (vector-ref xv n))

(let loop ((k 0) (lo 0) (hi 0) (min-lo 0) (max-d 0))

(if (= (vector-length xv) k)

(list lo hi max-d)

(let* ((min-lo (if (< (x k) (x min-lo)) k min-lo))

(d (- (x k) (x min-lo))))

(if (< max-d d)

(loop (+ k 1) min-lo k min-lo d)

(loop (+ k 1) lo hi min-lo max-d))))))

For testing we explicitly test all the examples given in the problem definition, plus 1000 length-25 vectors chosen at random, plus 25 length-1000 vectors chosen at random:

`(define (max-diff-test)`

(assert (max-diff-quadratic #(4 3 9 1 8 2 6 7 5)) '(3 4 7))

(assert (max-diff-quadratic #(4 2 9 1 8 3 6 7 5)) '(1 2 7))

(assert (max-diff-quadratic #(4 3 9 1 2 6 7 8 5)) '(3 7 7))

(assert (max-diff-quadratic #(5 4 3)) '(0 0 0))

(assert (max-diff-quadratic #(1 3 3)) '(0 1 2))

(assert (max-diff-linear #(4 3 9 1 8 2 6 7 5)) '(3 4 7))

(assert (max-diff-linear #(4 2 9 1 8 3 6 7 5)) '(1 2 7))

(assert (max-diff-linear #(4 3 9 1 2 6 7 8 5)) '(3 7 7))

(assert (max-diff-linear #(5 4 3)) '(0 0 0))

(assert (max-diff-linear #(1 3 3)) '(0 1 2))

(do ((i 0 (+ i 1))) ((= i 1000))

(let ((x (list->vector (shuffle (range 1 25)))))

(assert (max-diff-quadratic x) (max-diff-linear x))))

(do ((i 0 (+ i 1))) ((= i 25))

(let ((x (list->vector (shuffle (range 1 1000)))))

(assert (max-diff-quadratic x) (max-diff-linear x)))))

Range, assert, randint and shuffle are from the Standard Prelude. You can run the program at http://programmingpraxis.codepad.org/SlkN9AOJ.

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: