Maximum Difference in Array with j > i (C Program)
C
Hard
4 views
Problem Description
Finding the maximum difference of RR[j] - RR[i] where j > i - logic to update the max difference while tracking the minimum element?
Official Solution
#include <stdio.h>
int main() {
int RR[100], n;
printf("Enter number of elements: ");
scanf("%d", &n);
if (n < 2) {
printf("Array should have at least 2 elementsn");
return 0;
}
printf("Enter array elements:n");
for (int i = 0; i < n; i++) scanf("%d", &RR[i]);
int minSoFar = RR[0];
int maxDiff = RR[1] - RR[0];
for (int j = 1; j < n; j++) {
int diff = RR[j] - minSoFar;
if (diff > maxDiff) maxDiff = diff;
if (RR[j] < minSoFar) minSoFar = RR[j];
}
printf("Maximum difference RR[j] - RR[i] where j > i = %dn", maxDiff);
return 0;
}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!