chore(CPlusPlus): add maximum difference (#464)

pull/477/head^2
khushisinha20 2021-09-22 23:25:22 +05:30 committed by GitHub
parent 36204a35bb
commit 270bde42ed
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 33 additions and 0 deletions

View File

@ -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 <bits/stdc++.h>
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

View File

@ -14,6 +14,7 @@
10. [Quick Selection](Arrays/quick-select.cpp) 10. [Quick Selection](Arrays/quick-select.cpp)
11. [Remove Duplicates](Arrays/remove-duplicates.cpp) 11. [Remove Duplicates](Arrays/remove-duplicates.cpp)
12. [Leaders In The Array](Arrays/leaders-in-array.cpp) 12. [Leaders In The Array](Arrays/leaders-in-array.cpp)
13. [Maximum Difference](Arrays/maximum-difference.cpp)
## Dynamic-Programming ## Dynamic-Programming