A Pair with the Maximal Difference
Problem: A pair contains two numbers, and its second number is on the right side of the first one in an array. The difference of a pair is the minus result while subtracting the second number from the first one. Please implement a function which gets the maximal difference of all pairs in an array. For example, the maximal difference in the array {2, 4, 1, 16, 7, 5, 11, 9} is 11, which is the minus result of pair (16, 5).
从右往左扫描数组,总是和最小的元素计算diff
#include <stdio.h>
int max_diff(int data[], int n)
{
int min;
int diff, m_diff;
int i = n - 1;
diff = data[i-1] - data[i];
m_diff = diff;
min = data[i];
if (data[i-1] < min)
min = data[i-1];
i = i - 2;
while (i >= 0) {
diff = data[i] - min;
if (diff > m_diff)
m_diff = diff;
if (data[i] < min)
min = data[i];
i--;
}
return m_diff;
}
int main()
{
int data[] = {2, 4, 1, 16, 7, 5, 11, 9};
int n = 8;
printf("%d\n", max_diff(data, n));
return 0;
}