In this Java tutorial, we are given an array of integers, we have to find the maximal possible sum of its k consecutive elements.
Let us look into an example to understand the idea behind the statement
For input array =[ 2, 3, 7, 1, 6] and k=2, the output should be MaxConsecutiveSum(input array, k) =10
All possible sums of 2 consecutive elements are :
2+3=5, 3+7=10, 7+1=8, 1+6=7
Among all these possibilities 10 is the highest.
public class ArrayMax {
public static void main(String[] args) {
int[] arr={2,3,7,1,6};
System.out.println("The Maximum consecutive array sum is "+arrayMaxConsecutiveSum(arr,2));
}
public static int arrayMaxConsecutiveSum(int[] inputArray, int k) {
int sum=0;
for(int i=0;(i+k-1)<inputArray.length;i++){
int sum1=inputArray[i];
for(int j=i+1,l=0;l<(k-1)&&j<inputArray.length;j++,++l){
sum1=sum1+inputArray[j];
}
if(sum1>sum){
sum=sum1;
}
sum1=0;
}
return sum;
}
}
Input:
integer k
An integer not greater than the length of the array
i.e 1<= k <= array length
Output:
integer
The maximum possible sum
Submitted by Matam Deekshith (deekshithmatam)
Download packets of source code on Coders Packet
Comments