Thursday, November 26, 2015

Algorithm : Maximal possible sum of some consecutive items in an integer array


Lets think of an array like,
[ 2, 3, 8, 1, 12, 2, 4, 5]

In this array maximum sum of any 2 consecutive numbers is 14(12+2) and maximum sum of any 3 consecutive numbers is 21(8+1+12).

Here is a simple algorithm using Java for find the maximum sum of some consecutive numbers in an integer array. This is just a simple solution for this problem.

Feel free to add a comment if anyone has a optimized solution or anything hard to understand.

static int  arrayMaxConsecutiveSum(int[] inputArray, int k) {
 int result = 0; 
 int currentSum = 0; 
 for (int i = 0; i < k - 1; i++) { 
  currentSum += inputArray[i]; 
 } 
 for (int i = k - 1; i < inputArray.length; i++) {
  currentSum += inputArray[i] ; 
  if (currentSum > result) {
   result = currentSum; 
  } 
  currentSum -= inputArray[i - k + 1]; 
 } 
 return result; 
}


Go to this link to find out how to implement this code in Java

No comments:

Post a Comment

Optimize you working enviorenment : Single command to create & move to a directory in linux (C Shell, Bash)

Usually move to a directory just after creating is bit of a anxious task specially if the directory name is too long. mkdir long-name-of...