数对之差的最大值[算法]-分治法

题目:在数组中,数字减去它右边的数字得到一个数对之差。求所有数对之差的最大值。例如在数组{2, 4, 1, 16, 7, 5, 11, 9}中,数对之差的最大值是11,是16减去5的结果。

  public class MaxDiffer
    {
        /*Calculate the max value which is generated by the number substract
         * the number which is in the right side of the array
         * 
*/
        private int[] arrayNumbers = null;

        public MaxDiffer(int[] array)
        {
            arrayNumbers = array;
        }

        public int MaxDiffCalculation()
        {
            if (arrayNumbers.Length < 2 || arrayNumbers == null)
            {
                return 0;
            }
            else
            {
                int max = 0, min = 0;
                return DivideMaxDiffCore(0, arrayNumbers.Length - 1ref max, ref min);
            }
        }

        private int DivideMaxDiffCore(int startIndex, int endIndex, ref int max, ref int min)
        {
            if (startIndex == endIndex)
            {
                max = arrayNumbers[startIndex];
                min = arrayNumbers[startIndex];
                return 0;
            }
            else
            {
                int middleIndex = startIndex + (endIndex - startIndex) / 2;

                int leftMax = 0, leftMin = 0;
                int leftDiff = DivideMaxDiffCore(startIndex, middleIndex, ref leftMax, ref leftMin);

                int rightMax = 0, rightMin = 0;
                int rightDiff = DivideMaxDiffCore(middleIndex + 1, endIndex, ref rightMax, ref rightMin);

                int crossDiff = leftMax - rightMin;

                max = leftMax > rightMax ? leftMax : rightMax;
                min = rightMin < leftMin ? rightMin : leftMin;

                int maxDiff = leftDiff > rightDiff ? leftDiff : rightDiff;
                maxDiff = maxDiff > crossDiff ? maxDiff : crossDiff;

                return maxDiff;
            }
        }
    }
posted @ 2011-12-18 16:11  xpwilson  阅读(492)  评论(0编辑  收藏  举报