Skip to content

Instantly share code, notes, and snippets.

@ylegall
Created November 13, 2013 18:32
Show Gist options
  • Save ylegall/7453970 to your computer and use it in GitHub Desktop.
Save ylegall/7453970 to your computer and use it in GitHub Desktop.
Given an array A, find the maxium difference, D = A[j] - A[i] such that j >= i
import std.stdio;
import std.algorithm;
auto maxDiff(T)(T[] array) {
T m = 0, minVal = array[0];
foreach (i; 1 .. array.length) {
auto diff = array[i] - minVal;
m = max(m, diff);
minVal = min(minVal, array[i]);
}
return m;
}
void main() {
auto array = [15,2,5,3,10,7,-4];
writeln(maxDiff(array));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment