Partial Sums for Arrays

Anand B's avatarLearning and Sharing experience

Problem Statement:

Add the numbers between the lower index and upper index in an array

Inputs :

  1. A random array of both positive numbers and negative numbers.
  2. The function should accept two parameters namely, the Lower index and the Upper index.

Example :

let’s consider the below inputs and try to understand the solution.

arr = [3, 5, 6, 7, 2, -4, 10, 8];
lowerIndex = 1;
upperindex = 6;

Solution 1:

Code Snippet:

var sum = 0;
for (i = 0 => n) // n = end of the array
{
if(i <= 1 && i>=5)

     {
        sum =+ arr[i];
     }
}

Approach:

  1. Iterate the complete array.
  2. Check the index using the if loop. If it’s within the specified lower index and upper index.
  3. Add the numbers to the sum variable.
  4. The complexity of this implementation is O(n)

Solution 2:

Code Snippet:

var…

View original post 54 more words