Encuentre la suma máxima por pares en la lista vinculada que sea equidistante del frente y el reverso

Dada una lista enlazada lis de longitud N , donde N es par. La tarea es maximizar la suma de dos Nodes equidistantes de los extremos anterior y posterior de la lista enlazada dada.

Nota: dos Nodes ( i y j ) son equidistantes de ambos extremos si la distancia del i-ésimo Node desde el frente es la misma que la distancia del j-ésimo Node desde atrás .

Ejemplos:

Entrada: lis = {5, 4, 2, 1}
Salida: 6
Explicación: Los Nodes con pares presentes en esta lista enlazada son: El
Node 0 y el Node 3 son equidistantes teniendo una suma de 5 + 1 = 6.
Node 1 y Node 2 son equidistantes teniendo una suma de 4 + 2 = 6.
Por lo tanto, la suma máxima de Nodes equidistantes de la lista enlazada es max(6, 6) = 6. 

Entrada: lis = {4, 2, 2, 3}
Salida: 7
Explicación: Los Nodes con pares presentes en esta lista enlazada son: El
Node 0 y el Node 3 son equidistantes teniendo una suma de 4 + 3 = 7.
Node 1 y Node 2 son equidistantes teniendo una suma de 2 + 2 = 4.
Por lo tanto, la suma máxima de Nodes equidistantes de la lista enlazada es max(7, 4) = 7. 

 

Enfoque: la solución se basa en dividir la lista enlazada en dos mitades iguales y luego usar el enfoque de dos punteros . Siga los pasos que se mencionan a continuación para resolver el problema:

  • Obtenga la mitad y separe la lista enlazada en dos partes.
  • Invierta la segunda parte , para atravesarla en la dirección de avance.
  • Recorra en ambas partes y obtenga la suma máxima.
  • Recupere la lista enlazada nuevamente, conectando las partes nuevamente, para una buena práctica.

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

C++

// C++ code to implement above approach
#include <bits/stdc++.h>
using namespace std;
 
// Structure of a node
struct ListNode {
    int val;
    ListNode* next;
    ListNode()
        : val(0), next(nullptr)
    {
    }
    ListNode(int x)
        : val(x), next(nullptr)
    {
    }
    ListNode(int x, ListNode* next)
        : val(x), next(next)
    {
    }
};
 
// Function to add node in linked list
void push(struct ListNode** head_ref,
          int new_data)
{
    // Allocate node
    struct ListNode* new_node
        = new ListNode;
 
    // Put in the data
    new_node->val = new_data;
 
    // Link the old list off the new node
    new_node->next = (*head_ref);
 
    // Move the head to point the new node
    (*head_ref) = new_node;
}
 
// Function for reversing the linked list
void reverse(ListNode** head)
{
    ListNode *curr = *head, *prev = 0, *nxt;
 
    while (curr)
        nxt = curr->next,
        curr->next = prev,
        prev = curr,
        curr = nxt;
 
    *head = prev;
}
 
// Function to find the maximum sum
// of equidistant elements
int pairSum(ListNode* head)
{
 
    // Get mid and separate
    // the linked list into two parts
    ListNode *prev = 0, *slow = head,
             *fast = head;
 
    // Find mid
    while (fast and fast->next)
        prev = slow, slow = slow->next,
        fast = fast->next->next;
 
    // Separate them
    prev->next = 0;
 
    // Reverse the second part,
    // for traversing it
    // in forward direction
    reverse(&slow);
 
    // Traverse in both parts and
    // get the maximum sum
    int sum = 0;
    ListNode *ptr1 = head, *ptr2 = slow;
 
    while (ptr1)
        sum = max(sum, (ptr1->val
                        + ptr2->val)),
        ptr1 = ptr1->next, ptr2
                           = ptr2->next;
 
    // Recover the Linked List again, by
    // connection the parts again
    reverse(&slow);
    prev->next = slow;
 
    // Return sum
    return sum;
}
 
// Driver code
int main()
{
    struct ListNode* head = NULL;
    push(&head, 4);
    push(&head, 2);
    push(&head, 2);
    push(&head, 3);
 
    cout << pairSum(head);
    return 0;
}

Java

// Java code to implement above approach
class GFG{
 
// Structure of a node
static class ListNode {
    int val;
    ListNode next;
    ListNode()
    {
        this(0);
         
    }
    ListNode(int x)
    {
        this.val = x;
        this.next = null;
    }
    ListNode(int x, ListNode next)
    {
        this.val = x;
        this.next = next;
    }
};
 
// Function to add node in linked list
static ListNode push(ListNode head_ref,
          int new_data)
{
    // Allocate node
    ListNode new_node
        = new ListNode();
 
    // Put in the data
    new_node.val = new_data;
 
    // Link the old list off the new node
    new_node.next = head_ref;
 
    // Move the head to point the new node
    head_ref = new_node;
    return head_ref;
}
 
// Function for reversing the linked list
static ListNode reverse(ListNode head)
{
    ListNode curr = head, prev = new ListNode(), nxt=new ListNode();
 
    while (curr.next!=null) {
        nxt = curr.next;
        curr.next = prev;
        prev = curr;
        curr = nxt;
    }
    head = prev;
    return head;
}
 
// Function to find the maximum sum
// of equidistant elements
static int pairSum(ListNode head)
{
 
    // Get mid and separate
    // the linked list into two parts
    ListNode prev = new ListNode(), slow = head,
             fast = head;
 
    // Find mid
    while (fast!=null && fast.next!=null) {
        prev = slow;
        slow = slow.next;
        fast = fast.next.next;
    }
 
    // Separate them
    prev.next = new ListNode();
 
    // Reverse the second part,
    // for traversing it
    // in forward direction
    slow = reverse(slow);
 
    // Traverse in both parts and
    // get the maximum sum
    int sum = 0;
    ListNode ptr1 = head, ptr2 = slow;
 
    while (ptr1!=null) {
        sum = Math.max(sum, (ptr1.val
                        + ptr2.val));
        ptr1 = ptr1.next;
        ptr2 = ptr2.next;
    }
    // Recover the Linked List again, by
    // connection the parts again
    slow = reverse(slow);
    prev.next = slow;
 
    // Return sum
    return sum;
}
 
// Driver code
public static void main(String[] args)
{
    ListNode head = new ListNode();
    head = push(head, 4);
    head = push(head, 2);
    head = push(head, 2);
    head = push(head, 3);
 
    System.out.print(pairSum(head));
}
}
 
// This code is contributed by 29AjayKumar

C#

// C# code to implement above approach
using System;
 
public class GFG{
 
  // Structure of a node
  class ListNode {
    public int val;
    public ListNode next;
    public ListNode()
    {
      new ListNode(0);
 
    }
    public ListNode(int x)
    {
      this.val = x;
      this.next = null;
    }
    public ListNode(int x, ListNode next)
    {
      this.val = x;
      this.next = next;
    }
  };
 
  // Function to add node in linked list
  static ListNode push(ListNode head_ref,
                       int new_data)
  {
    // Allocate node
    ListNode new_node
      = new ListNode();
 
    // Put in the data
    new_node.val = new_data;
 
    // Link the old list off the new node
    new_node.next = head_ref;
 
    // Move the head to point the new node
    head_ref = new_node;
    return head_ref;
  }
 
  // Function for reversing the linked list
  static ListNode reverse(ListNode head)
  {
    ListNode curr = head, prev = new ListNode(), nxt=new ListNode();
 
    while (curr.next!=null) {
      nxt = curr.next;
      curr.next = prev;
      prev = curr;
      curr = nxt;
    }
    head = prev;
    return head;
  }
 
  // Function to find the maximum sum
  // of equidistant elements
  static int pairSum(ListNode head)
  {
 
    // Get mid and separate
    // the linked list into two parts
    ListNode prev = new ListNode(), slow = head,
    fast = head;
 
    // Find mid
    while (fast!=null && fast.next!=null) {
      prev = slow;
      slow = slow.next;
      fast = fast.next.next;
    }
 
    // Separate them
    prev.next = new ListNode();
 
    // Reverse the second part,
    // for traversing it
    // in forward direction
    slow = reverse(slow);
 
    // Traverse in both parts and
    // get the maximum sum
    int sum = 0;
    ListNode ptr1 = head, ptr2 = slow;
 
    while (ptr1!=null) {
      sum = Math.Max(sum, (ptr1.val
                           + ptr2.val));
      ptr1 = ptr1.next;
      ptr2 = ptr2.next;
    }
    // Recover the Linked List again, by
    // connection the parts again
    slow = reverse(slow);
    prev.next = slow;
 
    // Return sum
    return sum;
  }
 
  // Driver code
  public static void Main(String[] args)
  {
    ListNode head = new ListNode();
    head = push(head, 4);
    head = push(head, 2);
    head = push(head, 2);
    head = push(head, 3);
 
    Console.Write(pairSum(head));
  }
}
 
// This code is contributed by shikhasingrajput
Producción

7

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

Publicación traducida automáticamente

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