数组元素的总和,不包括位于 a 和 b 之间的元素
给定一个包含 N 个唯一数字的数组。还给定了两个数字a和b ,使得a在数组中始终位于b之前。任务是找出数组元素的总和,不包括位于 a 和 b 之间的元素。
例子:
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
方法:在数组中遍历,不断添加数组元素,直到找到a。继续迭代直到找到 b 并且不要将数组元素添加到总和中。找到b后,将数组元素添加到总和中直到最后。迭代完成后,返回总和。
下面是上述方法的实现:
C++
// CPP implementation of above approach
#include
using namespace std;
// Function to find sum
// of array excluding the
// range which has [a, b]
void sumexcludingrange(vectorli, int a, int b)
{
int sum = 0;
bool add = true;
// loop in li
int n = li.size();
for (int i = 0;i < n; i++)
{
// if no != a then add
if (li[i] != a &&
add == true)
sum = sum + li[i];
// mark when a
// and b are found
else if (li[i] == a)
add = false;
else if( li[i] == b)
add = true;
}
// print sum
cout<<(sum);
}
// Driver Code
int main()
{
vectorlis{1, 2, 4, 5, 6};
int a = 2;
int b = 5;
sumexcludingrange(lis, a, b);
}
// This code is contributed by
// Sahil_Shelangia
Java
// Java implementation of above approach
// Function to find sum
// of array excluding the
// range which has [a, b]
import java .io.*;
class GFG
{
static void sumexcludingrange(int li[],
int a, int b)
{
int sum = 0;
boolean add = true;
// loop in li
for (int i = 0;
i < li.length; i++)
{
// if no != a then add
if (li[i] != a &&
add == true)
sum = sum + li[i];
// mark when a
// and b are found
else if (li[i] == a)
add = false;
else if( li[i] == b)
add = true;
}
// print sum
System.out.print(sum);
}
// Driver Code
public static void main(String[] args)
{
int lis[] = {1, 2, 4, 5, 6};
int a = 2;
int b = 5;
sumexcludingrange(lis, a, b);
}
}
// This code is contributed
// by anuj_67.
Python3
# Python3 implementation of above approach
# Function to find sum
# of array excluding the
# range which has [a, b]
def sumexcludingrange(li, a, b):
sum = 0
add = True
# loop in li
for no in li:
# if no != a then add
if no != a and add == True:
sum = sum + no
# mark when a and b are found
elif no == a:
add = False
elif no == b:
add = True
# print sum
print (sum)
lis = [1, 2, 4, 5, 6]
a = 2
b = 5
sumexcludingrange(lis, a, b)
C#
// C# implementation of above approach
// Function to find sum
// of array excluding the
// range which has [a, b]
using System;
class GFG
{
static void sumexcludingrange(int[] li,
int a, int b)
{
int sum = 0;
bool add = true;
// loop in li
for (int i = 0;
i < li.Length; i++)
{
// if no != a then add
if (li[i] != a &&
add == true)
sum = sum + li[i];
// mark when a
// and b are found
else if (li[i] == a)
add = false;
else if( li[i] == b)
add = true;
}
// print sum
Console.Write(sum);
}
// Driver Code
public static void Main()
{
int[] lis = {1, 2, 4, 5, 6};
int a = 2;
int b = 5;
sumexcludingrange(lis, a, b);
}
}
Javascript
输出:
7