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


In array "A" maximum sum of any 2 consecutive numbers is 14(12+2) and maximum sum of any 3 consecutive numbers is 21(8+1+12).
     A=[ 2, 3, 8, 1, 12, 2, 4, 5]

Here is a simple algorithm using JavaScript 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.



function arrayMaxConsecutiveSum(inputArray, k) {
 var result = 0, currentSum = 0; 
 for (var i = 0; i < k - 1; i++) { 
  currentSum += inputArray[i]; 
 } 
 for (var i = k - 1; i < inputArray.length; i++) {
  currentSum += inputArray[i] ; 
  if (currentSum > result) {
   result = currentSum; 
  } 
  currentSum -= inputArray[i - k + 1]; 
 } 
 return result; 
} 
If you are using there won't be much difference in the code.
You can find a solution using Java from here.

No comments:

Post a Comment