RSS

Program to find Maximum sum of subset in array

Sun, Jun 29, 2008

Inverview Tips, Programming, Tutorials

Write a program to find maximum sum of subset in integer array. This is frequently asked interview question in Microsoft, Google and Amazon for position of SDE/SDET. I came up with efficient O(n) solution for this problem. If you have other solution to this problem; Please feel free to comment. Let’s dive into problem.

Problem: Write a program to find maximum sum of subset in integer array.
Example: 
Given input: {3 2 8 9 -25 5 8 4 4 -3 5 3 -10};
The subset with the largest sum would be: {5 8 4 4 -3 5 3}
 
So answer should be:
Start: 5 End: 11

This is what I came up with:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace MaxSumSubSet
{
    class Program
    {
 
        static void Main(string[] args)
        {
            int[] nums = new int[] { 3, 2, 8, 9, -25, 5, 8, 4, 4, -3, 5, 3, -10 };
            int start = -2;
            int end = -2;         
            int max = 0;
            int sum = 0;
                for (int i = 0, j = 0; i < nums.Length; i++)
                {
                    sum += nums[i];
                    if (sum > max)
                    {
                        max = sum;
                        start = j;
                        end = i;
                    }
                    else if (sum < 0)
                    {
                        j = i + 1;
                        sum = 0;
                    }
                }           
            Console.WriteLine("Start:{0} End:{1}", start, end);
        }
    }
}

OUTPUT:

Start: 5 End: 11
Sharing ~ Helping Other:
  • Print
  • email
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • BlinkList
  • DZone
  • Slashdot
  • YahooMyWeb
  • StumbleUpon
  • Live
  • IndianPad
  • DotNetKicks
  • Technorati

Related Posts:

, , ,

This post was written by:

eXclusiveMinds - who has written 500 posts on eXclusiveMinds.


Contact the author

2 Comments For This Post

  1. Rohan Says:

    Thank you very much for this post. I have been looking for this solution since a month.

  2. eXclusiveMinds Says:

    It’s good to know you like our post. Keep in touch.

Leave a Reply

You must be logged in to post a comment.