Created
July 30, 2017 22:06
-
-
Save thmain/6a19b7ec40d94bc82b82757075fee54a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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