Índice de los elementos que son iguales a la suma de todos los elementos siguientes

Dada una array arr[] de N enteros positivos. La tarea es encontrar el índice de los elementos que son iguales a la suma de todos los elementos sucesivos. Si no existe tal elemento, imprima -1 .
Ejemplos: 
 

Entrada: arr[] = { 36, 2, 17, 6, 6, 5 } 
Salida: 0 2 
arr[0] = arr[1] + arr[2] + arr[3] + arr[4] + arr[ 5] 
arr[2] = arr[3] + arr[4] + arr[5]
Entrada: arr[] = {7, 25, 17, 7} 
Salida: -1 
 

Enfoque: mientras recorre la array dada arr[] desde el último índice, mantenga una variable de suma que almacene la suma de los elementos recorridos hasta ahora. Compara la suma con el elemento actual arr[i] . Si es igual, inserte el índice de este elemento en el vector de respuesta . Si el tamaño del vector de respuesta al final es 0, imprima -1 ; de lo contrario, imprima su contenido.
A continuación se muestra la implementación del enfoque anterior: 
 

C++

// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the valid indices
void find_idx(int arr[], int n)
{
 
    // Vector to store the indices
    vector<int> answer;
 
    // Initialise sum with 0
    int sum = 0;
 
    // Starting from the last element
    for (int i = n - 1; i >= 0; i--) {
 
        // If sum till now is equal to
        // the current element
        if (sum == arr[i]) {
            answer.push_back(i);
        }
 
        // Add current element to the sum
        sum += arr[i];
    }
 
    if (answer.size() == 0) {
        cout << "-1";
        return;
    }
 
    for (int i = answer.size() - 1; i >= 0; i--)
        cout << answer[i] << " ";
}
 
// Driver code
int main()
{
    int arr[] = { 36, 2, 17, 6, 6, 5 };
    int n = sizeof(arr) / sizeof(int);
 
    find_idx(arr, n);
 
    return 0;
}

Java

// Java implementation of the approach
import java.util.*;
 
class GFG
{
     
    // Function to find the valid indices
    static void find_idx(int arr[], int n)
    {
     
        // Vector to store the indices
        Vector answer = new Vector();
     
        // Initialise sum with 0
        int sum = 0;
     
        // Starting from the last element
        for (int i = n - 1; i >= 0; i--)
        {
     
            // If sum till now is equal to
            // the current element
            if (sum == arr[i])
            {
                answer.add(i);
            }
     
            // Add current element to the sum
            sum += arr[i];
        }
     
        if (answer.size() == 0)
        {
            System.out.println("-1");
            return;
        }
     
        for (int i = answer.size() - 1; i >= 0; i--)
            System.out.print(answer.get(i) + " ");
    }
     
    // Driver code
    public static void main (String[] args)
    {
        int arr[] = { 36, 2, 17, 6, 6, 5 };
        int n = arr.length;
     
        find_idx(arr, n);
    }
}
 
// This code is contributed by AnkitRai01

Python3

# Python3 implementation of the approach
 
# Function to find the valid indices
def find_idx(arr, n):
 
    # List to store the indices
    answer=[]
 
    # Initialise sum with 0
    _sum = 0
 
    # Starting from the last element
    for i in range(n - 1, -1, -1):
 
        # If sum till now is equal to
        # the current element
        if (_sum == arr[i]) :
            answer.append(i)
 
        # Add current element to the sum
        _sum += arr[i]
 
    if (len(answer) == 0) :
        print(-1)
        return
 
    for i in range(len(answer) - 1, -1, -1):
        print(answer[i], end = " ")
 
# Driver code
arr = [ 36, 2, 17, 6, 6, 5 ]
n = len(arr)
 
find_idx(arr, n)
 
# This code is contributed by
# divyamohan123

C#

// C# implementation of the approach
using System;
using System.Collections.Generic;
 
class GFG
{
     
    // Function to find the valid indices
    static void find_idx(int[] arr, int n)
    {
     
        // List to store the indices
        List<int> answer = new List<int>();
     
        // Initialise sum with 0
        int sum = 0;
     
        // Starting from the last element
        for (int i = n - 1; i >= 0; i--)
        {
     
            // If sum till now is equal to
            // the current element
            if (sum == arr[i])
            {
                answer.Add(i);
            }
     
            // Add current element to the sum
            sum += arr[i];
        }
     
        if (answer.Count == 0)
        {
            Console.WriteLine("-1");
            return;
        }
     
        for (int i = answer.Count - 1; i >= 0; i--)
            Console.Write(answer[i] + " ");
    }
     
    // Driver code
    public static void Main (String[] args)
    {
        int[] arr = { 36, 2, 17, 6, 6, 5 };
        int n = arr.Length;
     
        find_idx(arr, n);
    }
}
 
// This code is contributed by Ashutosh450

Javascript

<script>
// Javascript implementation of the approach
 
// Function to find the valid indices
function find_idx(arr, n) {
 
    // Vector to store the indices
    let answer = [];
 
    // Initialise sum with 0
    let sum = 0;
 
    // Starting from the last element
    for (let i = n - 1; i >= 0; i--) {
 
        // If sum till now is equal to
        // the current element
        if (sum == arr[i]) {
            answer.push(i);
        }
 
        // Add current element to the sum
        sum += arr[i];
    }
 
    if (answer.length == 0) {
        document.write("-1");
        return;
    }
 
    for (let i = answer.length - 1; i >= 0; i--)
        document.write(answer[i] + " ");
}
 
// Driver code
let arr = [36, 2, 17, 6, 6, 5];
let n = arr.length;
 
find_idx(arr, n);
 
// This code is contributed by gfgking
</script>
Producción: 

0 2

 

Publicación traducida automáticamente

Artículo escrito por namankhare42 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *