Maximum Sum of All Sub-arrays

Keep scanning through the array and calculating the maximum sub-array that ends at every position. The sub-array will either contain a range of numbers if the array has intermixed positive and negative values, or it will contain the least negative value if the array has only negative values.

Use Kadane’s algorithm which runs in O(n) time.

 

    class Program
    {
        static void Main(string[] args)
        {
            int[] arr = new int[] { 5, -2, 3, 18, -4, 29, 2, -5 };
            FindMaximumSumofAllSubArrays(arr);
            Console.ReadLine();
        }

        private static void FindMaximumSumofAllSubArrays(int[] arr)
        {
            List<int> arrList = new List<int>();
            int maxSumSoFar = -2147483648;
            int curSum = 0;
            //loop for for chcking if all numbers in an array are negative.
            foreach (int item in arr)
            {
                if (maxSumSoFar < item)
                {
                    maxSumSoFar = item;
                }
            }

            if (maxSumSoFar < 0)
            {
                Console.WriteLine("All Array Numbers are Negative and Maximum sum is " + maxSumSoFar);
                return;
            }
            maxSumSoFar = 0;
            foreach (int item in arr)
            {
                curSum += item;
                if (curSum > maxSumSoFar)
                {
                    maxSumSoFar = curSum;
                }
                if (curSum < 0)
                {
                    curSum = 0;
                }
            }
            Console.WriteLine(maxSumSoFar);
        }
    }
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s