diff --git a/algorithms/CPlusPlus/Arrays/maximum-difference.cpp b/algorithms/CPlusPlus/Arrays/maximum-difference.cpp new file mode 100644 index 00000000..562e53ad --- /dev/null +++ b/algorithms/CPlusPlus/Arrays/maximum-difference.cpp @@ -0,0 +1,32 @@ +//Maximum difference between two elements such that larger element appears after the smaller number +//In this method we keep track of the maximum difference found so far and the minimum value found so far. + +#include +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]); + } + return maxDiff; +} + +int main() { + int n; + cin >> n; + int a[n]; + for (int i = 0; i < n; ++i) + cin >> a[i]; + cout << maximumDifference(a, n); + return 0; +} + +//Time Complexity : O(n) +//Auxiliary Space : O(1) + +//Example test case: +//Input: 2 3 10 6 4 8 1 +//Output: 8 diff --git a/algorithms/CPlusPlus/README.md b/algorithms/CPlusPlus/README.md index 186abdde..79ec0149 100644 --- a/algorithms/CPlusPlus/README.md +++ b/algorithms/CPlusPlus/README.md @@ -14,6 +14,7 @@ 10. [Quick Selection](Arrays/quick-select.cpp) 11. [Remove Duplicates](Arrays/remove-duplicates.cpp) 12. [Leaders In The Array](Arrays/leaders-in-array.cpp) +13. [Maximum Difference](Arrays/maximum-difference.cpp) ## Dynamic-Programming