Wednesday, 23 September 2015

How to find continuous sequence with largest sum


You are given an array of integers both positive and negative integers.Find the continuous sequence with largest sum.

For Example:

Input:-{2,-8,3,-2,4,-10}
Output:-5(i.e {3,-2,4})


/**  
  *   
  */  
 /**  
  * @author Dixit  
  *   
  */  
 public class LargestSumSequence {  
      /**  
       * @param args  
       */  
      public static void main(String[] args) {  
           int a[]={2, -8, 3, -2, 4, -10};  
           System.out.println("Continuous sequence with Largest sum :"+getMaxSum(a));  
      }  
      public static int getMaxSum(int[] a) {  
           int maxsum = 0;  
           int sum = 0;  
           for (int i = 0; i < a.length; i++) {  
                sum += a[i];  
                if (maxsum < sum) {  
                     maxsum = sum;  
                } else if (sum < 0) {  
                     sum = 0;  
                }  
           }  
           return maxsum;  
      }  
 }  


Output:-  
 Continuous sequence with Largest sum :5 


Enjoy Programming

2 comments:

  1. I dont think the answer is 5 here.
    In this case, the largest sum is: 15 i.e. {3,-2,4,10}

    ReplyDelete
    Replies
    1. Thanks for the correction. Here the input value is {2,-8,3,-2,4,-10} not {2,-8,3,-2,4,10}.
      So it displays 5 as the result.

      Delete