From 90e832e6a4ed7fb35e1bc08431f2c5ffeb91c799 Mon Sep 17 00:00:00 2001 From: Avviishek Date: Fri, 27 Jan 2023 11:17:41 +0530 Subject: [PATCH] Update maximum-difference.cpp Minor change in the algorithm and variables --- algorithms/CPlusPlus/Arrays/maximum-difference.cpp | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/algorithms/CPlusPlus/Arrays/maximum-difference.cpp b/algorithms/CPlusPlus/Arrays/maximum-difference.cpp index 562e53ad..9e38cf7e 100644 --- a/algorithms/CPlusPlus/Arrays/maximum-difference.cpp +++ b/algorithms/CPlusPlus/Arrays/maximum-difference.cpp @@ -5,13 +5,14 @@ using namespace std; int maximumDifference(int a[], int n) { - int minVal = a[0]; //Initialized minimum value with the first element of the array. - int maxDiff = a[1] - a[0]; //Initialized maximum difference with the difference between first and second value - for (int j = 1; j < n; ++j) { - maxDiff = max(maxDiff, a[j] - minVal); - minVal = min(minVal, a[j]); + int minVal = INT_MAX; //Initialized minimum value with the max no + int ans = INT_MIN; //Initialized maximum difference with min value + for (int j = 0; j < n; ++j) { + //maxDiff = max(maxDiff, a[j] - minVal); + 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() {