You are on page 1of 1

CODING COMPETITION 2ND QUESTION

/**
* This is the 2nd program in the coding competition
* @author (Shoubhit Dash)
* @version (a version number or a date)
*/
import java.util.Scanner;
public class ContiguousArraySum
{
static int maxContiguousArraySum(int a[],int size)
{
int maxSum = 0, maxTest = 0;
//maxSum will store the final sum and maxTest is for contiguous sums the sum
for (int i=0;i<size;i++)
{
maxTest = maxTest + a[i];
if (maxTest < 0) //only check if maxTest is greater than 0
maxTest = 0;
else if (maxSum < maxTest)
//checks if the contiguous sum is greater than the previous contiguous sum
maxSum = maxTest;
}
return maxSum; //returning the maximum sum of contiguous array
}
public static void main(String[]args)
{
int n=0;
Scanner sc=new Scanner(System.in);
System.out.println("Enter no. of elements you want in the array");
n=sc.nextInt();
int a[]=new int[n];
System.out.println("Enter all elements");
for (int i=0;i<n;i++) //input
{
a[i]=sc.nextInt();
}
//invoking func. and printing
System.out.println("Maximum sum of contiguous array="+maxContiguousArraySum(a,n));
}
}

You might also like