Skip to content

Instantly share code, notes, and snippets.

@thmain
Created July 30, 2017 22:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thmain/6a19b7ec40d94bc82b82757075fee54a to your computer and use it in GitHub Desktop.
Save thmain/6a19b7ec40d94bc82b82757075fee54a to your computer and use it in GitHub Desktop.
public class MaxDifferenceDynamicProgramming {
public static int maxDifference(int [] A){
int size = A.length;
int maxDiff = -1;
int max_so_far = A[size-1]; //assign the last element
for (int i = size - 2 ; i >0 ; i--) {
if(max_so_far<A[i])
max_so_far = A[i];
else if(max_so_far>A[i])
maxDiff = Math.max(maxDiff,max_so_far-A[i]);
}
return maxDiff;
}
public static void main(String[] args) {
int [] A = { 12, 5, 1, 7, 3, 9, 5};
System.out.println("Maximum Difference between two elements A[i] and A[j] and where j > i: " + maxDifference(A));
}
}
@zsalab
Copy link

zsalab commented Jul 31, 2017

I think this code does not work well with input:
int [] A = { 1, 12, 5, 1, 7, 3, 9, 5};

The problem is the i >0 in the for loop, it should be i >= 0

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment