Saturday 12 January 2019

Maximum Sum of a Set of Contiguous Positive Numbers in an Array:

An Array contains random positive as well as negative numbers. It may contain a streak of positive numbers and then a few negative numbers. This behaviour can occur multiple times.

You need to find out the maximum sum out of all streaks of the positive numbers.

For example:

Input1: 6
Input2: {1,2,3-4,3,1}
Output: 6

Input2: 7
Input2: {-1,3,1,2,-1,2,7}
Output: 9

The explanation for First Example :

Input 1: Number of Elements in the array
Input 2: Array Elements
Output: Maximum Sum of a Set of Contagious Positive Number in an Array:
In the first example there are two contagious set of positive numbers:
{1,2,3} and {3,1}. for which the sum is: 6 and 4, so the maximum out of them is 6.

CODE:

package arrays;

import java.util.Scanner;

public class MaximumSumContPositiveNum
     {
     public static void main(String[] args)
     {

     int curSum = 0, maxSum = -1;

     Scanner sc = new Scanner(System.in);

     System.out.println("Enter the length of Array");

     int n = sc.nextInt();

     int ar[] = new int[n];

     System.out.println("Enter the array Elements");

     for (int i = 0; i < n; i++)
     {
          ar[i] = sc.nextInt();
     }
     for (int idx = 0; idx < n; idx++)
     {
          if (ar[idx] >= 0)
          {
               curSum = curSum + ar[idx];
               if (curSum > maxSum)
               {
                    maxSum = curSum;
               }
          
          else
          {
               curSum = 0;
          }
     }
     System.out.println("Maximum Sum of a Set of Contagious Positive Number in an Array is " + maxSum);
     }
}

OUTPUT:
Enter the length of Array
7
Enter the array Elements
-1 3 1 2 -1 2 7
Maximum Sum of a Set of Contagious Positive Number in an Array is 9