Sum of array elements excluding the elements which lie between a and b
Last Updated :
14 Oct, 2022
Given an array of N unique numbers. Also given two numbers a and b such that a will always be before b in the array. The task is to find the sum of the array elements excluding the elements which lie between a and b.
Examples:
Input : arr = [2, 1, 6, 9, 11], a = 6, b = 9
Output : 14
Input : arr = [1, 2, 4, 5, 6], a = 2, b = 5
Output : 7
Approach: Traverse in the array, keep adding the array elements until we find a. Continue iteration until b is found and do not add array elements to the sum. After b is found, add array elements to the sum till the end. Once the iteration is completed, return the sum.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void sumexcludingrange(vector< int > li, int a, int b)
{
int sum = 0;
bool add = true ;
int n = li.size();
for ( int i = 0; i < n; i++) {
if (li[i] != a && add == true )
sum = sum + li[i];
else if (li[i] == a)
add = false ;
else if (li[i] == b)
add = true ;
}
cout << (sum);
}
int main()
{
vector< int > lis{ 1, 2, 4, 5, 6 };
int a = 2;
int b = 5;
sumexcludingrange(lis, a, b);
}
|
Java
import java.io.*;
class GFG {
static void sumexcludingrange( int li[], int a, int b)
{
int sum = 0 ;
boolean add = true ;
for ( int i = 0 ; i < li.length; i++) {
if (li[i] != a && add == true )
sum = sum + li[i];
else if (li[i] == a)
add = false ;
else if (li[i] == b)
add = true ;
}
System.out.print(sum);
}
public static void main(String[] args)
{
int lis[] = { 1 , 2 , 4 , 5 , 6 };
int a = 2 ;
int b = 5 ;
sumexcludingrange(lis, a, b);
}
}
|
Python3
def sumexcludingrange(li, a, b):
sum = 0
add = True
for no in li:
if no ! = a and add = = True :
sum = sum + no
elif no = = a:
add = False
elif no = = b:
add = True
print ( sum )
lis = [ 1 , 2 , 4 , 5 , 6 ]
a = 2
b = 5
sumexcludingrange(lis, a, b)
|
C#
using System;
class GFG {
static void sumexcludingrange( int [] li, int a, int b)
{
int sum = 0;
bool add = true ;
for ( int i = 0; i < li.Length; i++) {
if (li[i] != a && add == true )
sum = sum + li[i];
else if (li[i] == a)
add = false ;
else if (li[i] == b)
add = true ;
}
Console.Write(sum);
}
public static void Main()
{
int [] lis = { 1, 2, 4, 5, 6 };
int a = 2;
int b = 5;
sumexcludingrange(lis, a, b);
}
}
|
Javascript
<script>
function sumexcludingrange(li, a, b)
{
let sum = 0;
let add = true ;
for (let i = 0; i < li.length; i++)
{
if (li[i] != a &&
add == true )
sum = sum + li[i];
else if (li[i] == a)
add = false ;
else if (li[i] == b)
add = true ;
}
document.write(sum);
}
let lis = [ 1, 2, 4, 5, 6 ];
let a = 2;
let b = 5;
sumexcludingrange(lis, a, b);
</script>
|
Time complexity: O(n)
Auxiliary space: O(1)
Share your thoughts in the comments
Please Login to comment...