0% found this document useful (0 votes)
112 views1 page

Shoubhit Dash

This Java program contains a method that finds the maximum sum of a contiguous subarray within a given array. It takes in an array and size as parameters, initializes two variables to track the maximum sum and current contiguous sum, iterates through the array updating the sums, and returns the overall maximum sum. The main method takes user input for array size and elements, calls the maxContiguousArraySum method, and prints the result.

Uploaded by

Shoubhit Dash
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
112 views1 page

Shoubhit Dash

This Java program contains a method that finds the maximum sum of a contiguous subarray within a given array. It takes in an array and size as parameters, initializes two variables to track the maximum sum and current contiguous sum, iterates through the array updating the sums, and returns the overall maximum sum. The main method takes user input for array size and elements, calls the maxContiguousArraySum method, and prints the result.

Uploaded by

Shoubhit Dash
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 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