Advertisement
dimipan80

Exams - Max Sum

Nov 23rd, 2014
194
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /* You are given an integer array arr, consisting of N integers. Find the maximum possible sum of consecutive numbers
  2. in arr. For example: if the array arr consists of the numbers 1, 6, -9, 4, 4, -2, 10, -1, the maximum possible sum
  3. of consecutive numbers is 16 (the consecutive numbers are 4, 4, -2 and 10). Element 0 of the array is the number N.
  4. Next N elements (from 1 to N) construct the array arr. Your method should return a single number -
  5. the maximum possible sum of consecutive numbers.*/
  6.  
  7. "use strict";
  8.  
  9. function solve(args) {
  10.     var maxSum = -2000001;
  11.     for (var i = 1; i < args.length; i += 1) {
  12.         var sum = 0;
  13.         for (var j = i; j < args.length; j += 1) {
  14.             sum += parseInt(args[j]);
  15.             if (sum > maxSum) {
  16.                 maxSum = sum;
  17.             }
  18.         }
  19.     }
  20.  
  21.     console.log(maxSum);
  22. }
  23.  
  24. solve([ '8', '1', '6', '-9', '4', '4', '-2', '10', '-1' ]);
  25. solve([ '6', '1', '3', '-5', '8', '7', '-6' ]);
  26. solve([ '9', '-9', '-8', '-8', '-7', '-6', '-5', '-1', '-7', '-6' ]);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement