Dada una array arr[] de tamaño N , la tarea es encontrar la subsecuencia no vacía más larga de la array dada cuya suma sea máxima.
Ejemplos:
Entrada: arr[] = { 1, 2, -4, -2, 3, 0 }
Salida: 1 2 3 0
Explicación:
La suma de los elementos de la subsecuencia {1, 2, 3, 0} es 6, que es el máximo suma posible.
Por lo tanto, la salida requerida es 1 2 3 0Entrada: arr[] = { -10, -6, -2, -3, -4 }
Salida: -2
Enfoque ingenuo: el enfoque más simple para resolver este problema es atravesar la array y generar todas las subsecuencias posibles de la array dada y calcular sus sumas. Imprime la más larga de todas las subsecuencias con suma máxima.
Complejidad de Tiempo: O(N * 2 N )
Espacio Auxiliar: O(N)
Enfoque eficiente: el problema se puede resolver utilizando la técnica Greedy . Siga los pasos a continuación para resolver el problema:
- Inicialice una variable, digamos maxm , para almacenar el elemento más grande de la array dada .
- Si maxm < 0 , imprima el valor de maxm .
- De lo contrario, recorra la array e imprima todos los elementos positivos de la array.
A continuación se muestra la implementación del enfoque anterior:
C++
// C++ program to implement // the above approach #include <bits/stdc++.h> using namespace std; // Function to find the longest subsequence // from the given array with maximum sum void longestSubWithMaxSum(int arr[], int N) { // Stores the largest element // of the array int Max = *max_element(arr, arr + N); // If Max is less than 0 if (Max < 0) { // Print the largest element // of the array cout << Max; return; } // Traverse the array for (int i = 0; i < N; i++) { // If arr[i] is greater // than or equal to 0 if (arr[i] >= 0) { // Print elements of // the subsequence cout << arr[i] << " "; } } } // Driver Code int main() { int arr[] = { 1, 2, -4, -2, 3, 0 }; int N = sizeof(arr) / sizeof(arr[0]); longestSubWithMaxSum(arr, N); return 0; }
Java
// Java program to implement // the above approach import java.util.*; class GFG{ // Function to find the longest subsequence // from the given array with maximum sum static void longestSubWithMaxSum(int arr[], int N) { // Stores the largest element // of the array int Max = Arrays.stream(arr).max().getAsInt(); // If Max is less than 0 if (Max < 0) { // Print the largest element // of the array System.out.print(Max); return; } // Traverse the array for(int i = 0; i < N; i++) { // If arr[i] is greater // than or equal to 0 if (arr[i] >= 0) { // Print elements of // the subsequence System.out.print(arr[i] + " "); } } } // Driver Code public static void main(String[] args) { int arr[] = { 1, 2, -4, -2, 3, 0 }; int N = arr.length; longestSubWithMaxSum(arr, N); } } // This code is contributed by code_hunt
Python3
# Python3 program to implement # the above approach # Function to find the longest subsequence # from the given array with maximum sum def longestSubWithMaxSum(arr, N): # Stores the largest element # of the array Max = max(arr) # If Max is less than 0 if (Max < 0) : # Print the largest element # of the array print(Max) return # Traverse the array for i in range(N): # If arr[i] is greater # than or equal to 0 if (arr[i] >= 0) : # Print elements of # the subsequence print(arr[i], end = " ") # Driver code arr = [ 1, 2, -4, -2, 3, 0 ] N = len(arr) longestSubWithMaxSum(arr, N) # This code is contributed divyeshrabadiya07
C#
// C# program to implement // the above approach using System; class GFG{ // Function to find the longest subsequence // from the given array with maximum sum static void longestSubWithMaxSum(int []arr, int N) { // Stores the largest element // of the array int Max = arr[0]; for(int i = 1; i < N; i++) { if (Max < arr[i]) Max = arr[i]; } // If Max is less than 0 if (Max < 0) { // Print the largest element // of the array Console.Write(Max); return; } // Traverse the array for(int i = 0; i < N; i++) { // If arr[i] is greater // than or equal to 0 if (arr[i] >= 0) { // Print elements of // the subsequence Console.Write(arr[i] + " "); } } } // Driver Code public static void Main(String[] args) { int []arr = { 1, 2, -4, -2, 3, 0 }; int N = arr.Length; longestSubWithMaxSum(arr, N); } } // This code is contributed by aashish1995
Javascript
<script> // JavaScript program to implement // the above approach // Function to find the longest subsequence // from the given array with maximum sum function longestSubWithMaxSum(arr, N) { // Stores the largest element // of the array let Max = Math.max(...arr); // If Max is less than 0 if (Max < 0) { // Print the largest element // of the array document.write(Max); return; } // Traverse the array for(let i = 0; i < N; i++) { // If arr[i] is greater // than or equal to 0 if (arr[i] >= 0) { // Print the elements of // the subsequence document.write(arr[i] + " "); } } } // Driver code let arr = [ 1, 2, -4, -2, 3, 0 ]; let N = arr.length; longestSubWithMaxSum(arr, N); // This code is contributed by avijitmondal1998 </script>
1 2 3 0
Complejidad temporal: O(N)
Espacio auxiliar: O(1)
Publicación traducida automáticamente
Artículo escrito por pushpendrayadav1057 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA