Program to find the maximum sum of elements in an array

This program will help you in finding the maximum sum of elements in an array. If all the elements are positive, the maximum sum is sum of all the elements in the array. If all the elements are negative, the maximum sum is the first element in array.

If array has both positive and negative elements, then we need to traverse the entire elements. Here, we are initializing 2 variables sum and maxsum as 0. For all the elements, we are adding to sum. If sum > maxsum, we will add those value to maxsum as well.


public class arraySum {

public static void main(String args[])
{
int array[] = {1,2,5,-3,-5,-6,11,13,-2,1,-5,4};
int maxsum = sum(array);
System.out.println(" Maximum sum = "+maxsum);
}


public static int sum(int arr[])
{
int sum=0;
int maxsum=0;
for(int i=0; i<arr.length;i++)
{
sum=sum+arr[i];
if(maxsum<sum)
{
maxsum=sum;
}
}
return maxsum;
}
}

Comments

Popular posts from this blog

Difference between "diff" and "sdiff" commands in Unix

Anonymous classes in C++