Número de grupos de imanes formados a partir de N imanes

Los N imanes dados se mantienen en fila uno tras otro, ya sea con un polo negativo a la izquierda y un polo positivo a la derecha (01) o un polo positivo a la izquierda y un polo negativo a la derecha (10). Considerando el hecho de que si 2 imanes consecutivos tienen polos diferentes uno frente al otro, forman un grupo y se atraen, encuentre el número total de grupos posibles.

Ejemplos :  

Entrada : N = 6, imanes = {10, 10, 10, 01, 10, 10}
Salida : 3
Explicación: Los grupos están formados por los siguientes imanes: {1, 2, 3}, {4}, {5, 6}

Entrada : N = 5, imanes = {10, 10, 10, 10, 10, 01}
Salida : 2

Consideremos cada par de imanes consecutivos. Hay 2 casos posibles:  

  • Ambos tienen la misma configuración. En este caso, los extremos de conexión tendrán polos diferentes y por lo tanto pertenecerían al mismo grupo.
  • Ambos tienen configuraciones diferentes. En este caso, los extremos de conexión tendrán el mismo polo y, por lo tanto, se repelerán para formar grupos diferentes.

Por lo tanto, solo se formará un nuevo grupo en el caso de que dos imanes consecutivos tengan configuraciones diferentes. Recorrer la array de imanes y encontrar el número de pares consecutivos con las diferentes configuraciones.

A continuación se muestra la implementación del enfoque anterior:  

C++

// C++ program to find number of groups
// of magnets formed from N magnets
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to count number of groups of
// magnets formed from N magnets
int countGroups(int n, string m[])
{
    // Intinially only a single group
    // for the first magnet
    int count = 1;
 
    for (int i = 1; i < n; i++)
 
        // Different configuration increases
        // number of groups by 1
        if (m[i] != m[i - 1])
            count++;
 
    return count;
}
 
// Driver Code
int main()
{
    int n = 6;
 
    string m[n] = { "10", "10", "10", "01", "10", "10" };
 
    cout << countGroups(n, m);
 
    return 0;
}

Java

// Java program to find the maximum number
// of elements that can be added to a set
// such that it is the absolute difference // of magnets formed from N magnets
 
import java.util.*;
import java.lang.*;
import java.io.*;
 
class GFG{ 
     
// Function to count number of groups of
// magnets formed from N magnets
static int countGroups(int n, String m[])
{
    // Intinially only a single group
    // for the first magnet
    int count = 1;
   
    for (int i = 1; i < n; i++)
   
        // Different configuration increases
        // number of groups by 1
        if (m[i] != m[i - 1])
            count++;
   
    return count;
}
   
// Driver Code
public static void main(String args[])
{
    int n = 6;
   
    String []m = { "10", "10", "10", "01", "10", "10" };
   
    System.out.println( countGroups(n, m));
   
}
}

Python 3

# Python 3 program to find number
# of groups of magnets formed
# from N magnets
 
# Function to count number of
# groups of magnets formed
# from N magnets
def countGroups(n, m):
 
    # Intinially only a single
    # group for the first magnet
    count = 1
 
    for i in range(1, n):
 
        # Different configuration increases
        # number of groups by 1
        if (m[i] != m[i - 1]):
            count += 1
 
    return count
 
# Driver Code
if __name__ == "__main__":
 
    n = 6
 
    m = [ "10", "10", "10",
          "01", "10", "10" ]
 
    print(countGroups(n, m))
 
# This code is contributed
# by ChitraNayal

C#

// C# program to find number of groups
// of magnets formed from N magnets
using System;
 
class GFG {
 
    // Function to count number of groups of
    // magnets formed from N magnets
    static int countGroups(int n, String []m)
    {
         
        // Intinially only a single group
        // for the first magnet
        int count = 1;
     
        for (int i = 1; i < n; i++)
     
            // Different configuration increases
            // number of groups by 1
            if (m[i] != m[i - 1])
                count++;
     
        return count;
}
 
// Driver Code
public static void Main()
{
    int n = 6;
    String [] m = {"10", "10", "10",
                    "01", "10", "10"};
 
    Console.WriteLine(countGroups(n, m));
}
}
 
// This code is contributed by ANKITRAI1

PHP

<?php
// PHP program to find number of groups
// of magnets formed from N magnets
 
// Function to count number of groups
// of magnets formed from N magnets
function countGroups($n, $m)
{
    // Intinially only a single group
    // for the first magnet
    $count = 1;
 
    for ($i = 1; $i < $n; $i++)
 
        // Different configuration increases
        // number of groups by 1
        if ($m[$i] != $m[$i - 1])
            $count++;
 
    return $count;
}
 
// Driver Code
$n = 6;
 
$m = array( "10", "10", "10",
            "01", "10", "10" );
 
echo(countGroups($n, $m));
 
// This code is contributed
// by Shivi_Aggarwal
?>

Javascript

<script>
// Javascript program to find the maximum number
// of elements that can be added to a set
// such that it is the absolute difference
// of magnets formed from N magnets
     
// Function to count number of groups of
// magnets formed from N magnets
function countGroups(n,m) {
    // Intinially only a single group
    // for the first magnet
    let count = 1;
     
    for (let i = 1; i < n; i++)
     
        // Different configuration increases
        // number of groups by 1
        if (m[i] != m[i - 1])
            count++;
     
    return count;
}
     
    // Driver Code
    let n = 6;
    let m=[ "10", "10", "10", "01", "10", "10"];
    document.write( countGroups(n, m));
     
 
// This code is contributed by rag2127
</script>
Producción

3

Complejidad temporal: O(N)
Espacio auxiliar: O(1)

Publicación traducida automáticamente

Artículo escrito por Abdullah Aslam 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 *