F
F
FromHellWithLove2018-08-21 21:14:22
Algorithms
FromHellWithLove, 2018-08-21 21:14:22

Implementation of the algorithm for finding the minimum sum of a continuous sequence, any options?

You need to write an algorithm for finding the minimum sum of a continuous sequence of n numbers in an array of size m Example: arr = [ 5, 7, 2, 3, 5, 12, 1, 1, 5] (m = 9) for n = 2 the answer is [1 , 1] for n = 3 the answer is [1, 1, 5].
There are options?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2018-08-21
@FromHellWithLove

function getMinSum(arr, n) {
  var
    sum = 0,
    minSum = 0,
    index = 0;

  for (var i = 0; i < n; i++) {
    sum += arr[i];
  }
  minSum = sum;

  for (var i = n; i < arr.length; i++) {
    sum = sum - arr[i - n] + arr[i];
    if (sum < minSum) {
      minSum = sum;
      index = i - n + 1;
    }
  }

  return {
    sum: minSum,
    seq: arr.slice(index, index + n)
  };
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question