Update maximum-difference.cpp
Minor change in the algorithm and variablespull/1144/head
parent
af47764be0
commit
90e832e6a4
|
@ -5,13 +5,14 @@
|
||||||
using namespace std;
|
using namespace std;
|
||||||
|
|
||||||
int maximumDifference(int a[], int n) {
|
int maximumDifference(int a[], int n) {
|
||||||
int minVal = a[0]; //Initialized minimum value with the first element of the array.
|
int minVal = INT_MAX; //Initialized minimum value with the max no
|
||||||
int maxDiff = a[1] - a[0]; //Initialized maximum difference with the difference between first and second value
|
int ans = INT_MIN; //Initialized maximum difference with min value
|
||||||
for (int j = 1; j < n; ++j) {
|
for (int j = 0; j < n; ++j) {
|
||||||
maxDiff = max(maxDiff, a[j] - minVal);
|
//maxDiff = max(maxDiff, a[j] - minVal);
|
||||||
minVal = min(minVal, a[j]);
|
minVal = min(minVal, a[j]); // extracting the min value upto index j
|
||||||
|
ans = max(ans , a[j] - minVal); // max difference with each passing index
|
||||||
}
|
}
|
||||||
return maxDiff;
|
return ans;
|
||||||
}
|
}
|
||||||
|
|
||||||
int main() {
|
int main() {
|
||||||
|
|
Loading…
Reference in New Issue