📌  相关文章
📜  元素的总和,直到最小的索引,使得它的右边没有偶数

📅  最后修改于: 2022-05-13 01:57:52.760000             🧑  作者: Mango

元素的总和,直到最小的索引,使得它的右边没有偶数

给定一个包含N个整数的数组arr[] 。任务是找到最小索引的元素总和,使得索引右侧没有偶数元素。请注意,该数组将至少有一个偶数元素。
例子:

方法:从数组中找到最右边偶数元素的索引,并返回从索引 0 开始到找到的索引的所有元素的总和。
下面是上述方法的实现:

C++
// C++ implementation of the approach
#include 
using namespace std;
 
// Function to return the required sum
int smallestIndexsum(int arr[], int n)
{
 
    // Starting from the last index
    int i = n - 1;
 
    // Skip all odd elements and find the
    // index of the rightmost even element
    while (i >= 0 && arr[i] % 2 == 1)
        i--;
 
    // To store the required sum
    int sum = 0;
    for (int j = 0; j <= i; j++)
        sum += arr[j];
 
    return sum;
}
 
// Driver code
int main()
{
 
    int arr[] = { 2, 3, 5, 6, 3, 3 };
    int n = sizeof(arr) / sizeof(arr[0]);
 
    cout << smallestIndexsum(arr, n);
 
    return 0;
}


Java
// Java implementation of the approach
class GFG
{
 
// Function to return the required sum
static int smallestIndexsum(int arr[], int n)
{
 
    // Starting from the last index
    int i = n - 1;
 
    // Skip all odd elements and find the
    // index of the rightmost even element
    while (i >= 0 && arr[i] % 2 == 1)
        i--;
 
    // To store the required sum
    int sum = 0;
    for (int j = 0; j <= i; j++)
        sum += arr[j];
 
    return sum;
}
 
// Driver code
public static void main(String[] args)
{
    int arr[] = { 2, 3, 5, 6, 3, 3 };
    int n = arr.length;
 
    System.out.println(smallestIndexsum(arr, n));
}
}
 
// This code is contributed by 29AjayKumar


Python3
# Python3 implementation of the approach
 
# Function to return the required sum
def smallestIndexsum(arr, n):
 
    # Starting from the last index
    i = n - 1;
 
    # Skip all odd elements and find the
    # index of the rightmost even element
    while (i >= 0 and arr[i] % 2 == 1):
        i -= 1;
 
    # To store the required sum
    sum = 0;
    for j in range(0, i + 1):
        sum += arr[j];
 
    return sum;
 
# Driver code
if __name__ == '__main__':
 
    arr = [ 2, 3, 5, 6, 3, 3 ];
    n = len(arr);
 
    print(smallestIndexsum(arr, n));
 
# This code is contributed by PrinciRaj1992


C#
// C# implementation of the approach
using System;
 
class GFG
{
     
// Function to return the required sum
static int smallestIndexsum(int []arr, int n)
{
 
    // Starting from the last index
    int i = n - 1;
 
    // Skip all odd elements and find the
    // index of the rightmost even element
    while (i >= 0 && arr[i] % 2 == 1)
        i--;
 
    // To store the required sum
    int sum = 0;
    for (int j = 0; j <= i; j++)
        sum += arr[j];
 
    return sum;
}
 
// Driver code
static public void Main ()
{
    int []arr = { 2, 3, 5, 6, 3, 3 };
    int n = arr.Length;
     
    Console.Write(smallestIndexsum(arr, n));
}
}
 
// This code is contributed by ajit.


Javascript


输出:
16

时间复杂度: O(N)

辅助空间: O(1)