Sei sulla pagina 1di 13

Distance Maximizing in Array

Yang Liu

Problem
Given an array of integers, find the maximum of j-i subject to that A[i]<A[j] Example Input: 5 2 3 1 7 Output: 4(=4-0)

Brute Force
For(dist=n-1; dist>=0; dist--) for(i=0; i<n-dist; i++) if(A[i+dist]>A[i] return dist;

O(n) Algorithm
Observation For input 5 2 3 1 7,
3 never could be i which maximize j-I since 2 is before 3. 1 never could be j since 1 is before 7

Idea:
Use lArray to store possible is. Use rArray to store possible js.

Possible is
k=0 I[k]=A[0] Iind[k]=0; For(i=1;i<n;i++) if(A[i]<I[k]) k=k+1; I[k]=A[i] Iind[k]=i;
A=9 7 3 1 10 2 8 6 5 4 I=9 7 3 1 Iind=0 1 2 3

Possible js
k=0 J[k]=A[n-1] Jind[k]=n-1; For(i=n-2;i>=0;i--) if(A[i]>J[k]) k=k+1; J[k]=A[i] Jind[k]=i;
A=9 7 3 1 10 2 8 6 5 4 J= Iind= 10 4 654 789

Finding Maximum Distance


I=9 7 3 1 Iind=0 1 2 3

9 7 3 1
The furthest i for J[0]

J= Iind=

10 4

654 789

10 6 5 4
dist: 4(=4-0)

Finding Maximum Distance


I=9 7 3 1 Iind=0 1 2 3

9 7 3 1
The furthest i for J[1]

J= Iind=

10 4

654 789

10 6 5 4
dist: 5(=7-2)

Finding Maximum Distance


I=9 7 3 1 Iind=0 1 2 3

9 7 3 1
The furthest i for J[2]

J= Iind=

10 4

654 789

10 6 5 4
dist: 6(=8-2)

Finding Maximum Distance


I=9 7 3 1 Iind=0 1 2 3

9 7 3 1
The furthest i for J[3]

J= Iind=

10 4

654 789

10 6 5 4
dist: 7(=9-2)

Finding Maximum Distance


Queue Q to store Iind Stack S to store Jind maxDist=0; While(S is not empty) jInd=S.pop(); while(Q is not empty) iInd=Q.front(); if(A[jInd]>A[iInd]) maxDist=(jInd-iInd>maxDist)?jIndiInd:maxDist;

Exercise 1
You have an array A such that A[i] is the price of a stock on day i. You are only permitted to buy one share of the stock and sell one share of the stock. Design an algorithm to find the best times to buy and sell.

Exercise 2
Given an array A, find maximum A[i]-A[j] where i<j Example Input: A: 2 9 3 1 4 Output: 8(=9-1)

Potrebbero piacerti anche