Update maximum-difference.cpp

Minor change in the algorithm and variables
pull/1144/head
Avviishek 2023-01-27 11:17:41 +05:30
parent af47764be0
commit 90e832e6a4
1 changed files with 7 additions and 6 deletions

View File

@ -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() {