算法思想借鉴自:http://blog.csdn.net/clamreason/article/details/7904062
由2个元素开始作为初始条件,一个一个元素的添加进现有数组,保存2个变量,1个是currMin,就是当前处理的子数组的最小元素,一个是maxDiff,就是当前处理的子数组中最大的数对之差。如果当前添加的元素比min小,更新min,如果当前添加的元素减去min比maxDiff大,那么更新maxDiff。
/* LeetCode: A Distance Maximizing Problem return value: max difference parameters: arr - the array, range [0, len-1] len - the length of the array */ int MaxDifference(int arr[], int len) { if (!arr || len < 2) return 0; int currMin = arr[0] < arr[1] ? arr[0] : arr[1]; //current min int maxDiff = arr[1] - arr[0]; //max difference for (int i = 2; i < len; i++) { if (maxDiff < arr[i] - currMin) maxDiff = arr[i] - currMin; if (arr[i] < currMin) currMin = arr[i]; } return maxDiff; }
EOF