コード例 #1
0
        /// <summary>
        /// T (nlogn) S O(1)
        /// </summary>
        /// <param name="arr"></param>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <returns></returns>
        private static MaxSubArray MaxSumSubArrayRecursion(int[] arr, int start, int end)
        {
            if (start == end)
            {
                return(new MaxSubArray()
                {
                    start = start, end = end, val = arr[start]
                });
            }

            if (start > end)
            {
                return(new MaxSubArray());
            }

            int mid = start + (end - start) / 2;

            MaxSubArray left   = MaxSumSubArrayRecursion(arr, start, mid - 1);
            MaxSubArray right  = MaxSumSubArrayRecursion(arr, mid + 1, end);
            MaxSubArray middle = GetMaxMiddle(arr, start, end, mid);

            // find the max of left right and middle.f
            MaxSubArray max = left.val < right.val ? right : left;

            max = max.val < middle.val ? middle : max;

            return(max);
        }
コード例 #2
0
        /// <summary>
        /// T: O(n^3) S: O(1)
        /// </summary>
        /// <param name="arr"></param>
        /// <returns></returns>
        private static MaxSubArray MaxSumSubArrayBF(int[] arr)
        {
            MaxSubArray result = new MaxSubArray();

            for (int start = 0; start < arr.Length; start++)
            {
                for (int end = start; end < arr.Length; end++)
                {
                    int value = 0;
                    for (int i = start; i <= end; i++)
                    {
                        value += arr[i];
                    }

                    if (value > result.val)
                    {
                        result.start = start;
                        result.end   = end;
                        result.val   = value;
                    }
                }
            }

            return(result);
        }
コード例 #3
0
        /// <summary>
        /// T: O(n^2) S: O(1)
        /// </summary>
        /// <param name="arr"></param>
        /// <returns></returns>
        private static MaxSubArray MaxSumSubArrayBFImproved(int[] arr)
        {
            MaxSubArray result = new MaxSubArray();

            for (int start = 0; start < arr.Length; start++)
            {
                int cumSum = 0;

                for (int end = start; end < arr.Length; end++)
                {
                    cumSum += arr[end];

                    if (cumSum > result.val)
                    {
                        result.start = start;
                        result.end   = end;
                        result.val   = cumSum;
                    }
                }
            }

            return(result);
        }