Sum of elements till the smallest index such that there are no even numbers to its right
Last Updated :
06 Nov, 2021
Given an array arr[] of N integers. The task is to find the sum of elements to the smallest index such that there are no even elements to the right of the index. Note that the array will have at least one even element.
Examples:
Input: arr[] = {2, 3, 5, 6, 3, 3}
Output: 16
2 + 3 + 5 + 6 = 16
Input: arr[] = {3, 4}
Output: 7
3 + 4 = 7
Approach: Find the index of the rightmost even element from the array and return the sum of all the elements starting from index 0 to the found index.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int smallestIndexsum( int arr[], int n)
{
int i = n - 1;
while (i >= 0 && arr[i] % 2 == 1)
i--;
int sum = 0;
for ( int j = 0; j <= i; j++)
sum += arr[j];
return sum;
}
int main()
{
int arr[] = { 2, 3, 5, 6, 3, 3 };
int n = sizeof (arr) / sizeof (arr[0]);
cout << smallestIndexsum(arr, n);
return 0;
}
|
Java
class GFG
{
static int smallestIndexsum( int arr[], int n)
{
int i = n - 1 ;
while (i >= 0 && arr[i] % 2 == 1 )
i--;
int sum = 0 ;
for ( int j = 0 ; j <= i; j++)
sum += arr[j];
return sum;
}
public static void main(String[] args)
{
int arr[] = { 2 , 3 , 5 , 6 , 3 , 3 };
int n = arr.length;
System.out.println(smallestIndexsum(arr, n));
}
}
|
Python3
def smallestIndexsum(arr, n):
i = n - 1 ;
while (i > = 0 and arr[i] % 2 = = 1 ):
i - = 1 ;
sum = 0 ;
for j in range ( 0 , i + 1 ):
sum + = arr[j];
return sum ;
if __name__ = = '__main__' :
arr = [ 2 , 3 , 5 , 6 , 3 , 3 ];
n = len (arr);
print (smallestIndexsum(arr, n));
|
C#
using System;
class GFG
{
static int smallestIndexsum( int []arr, int n)
{
int i = n - 1;
while (i >= 0 && arr[i] % 2 == 1)
i--;
int sum = 0;
for ( int j = 0; j <= i; j++)
sum += arr[j];
return sum;
}
static public void Main ()
{
int []arr = { 2, 3, 5, 6, 3, 3 };
int n = arr.Length;
Console.Write(smallestIndexsum(arr, n));
}
}
|
Javascript
<script>
function smallestIndexsum(arr, n)
{
let i = n - 1;
while (i >= 0 && arr[i] % 2 == 1)
i--;
let sum = 0;
for (let j = 0; j <= i; j++)
sum += arr[j];
return sum;
}
let arr = [ 2, 3, 5, 6, 3, 3 ];
let n = arr.length;
document.write(smallestIndexsum(arr, n));
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...