Dada una array arr[] de enteros, averigüe la diferencia máxima entre dos elementos, de modo que el elemento más grande aparezca después del número más pequeño.
Ejemplos:
Input : arr = {2, 3, 10, 6, 4, 8, 1} Output : 8 Explanation : The maximum difference is between 10 and 2. Input : arr = {7, 9, 5, 6, 3, 2} Output : 2 Explanation : The maximum difference is between 9 and 7.
Método 1 (Simple)
Use dos bucles. En el ciclo externo, elija los elementos uno por uno y en el ciclo interno calcule la diferencia del elemento seleccionado con todos los demás elementos de la array y compare la diferencia con la diferencia máxima calculada hasta el momento. A continuación se muestra la implementación del enfoque anterior:
C++
// C++ program to find Maximum difference // between two elements such that larger // element appears after the smaller number #include <bits/stdc++.h> using namespace std; /* The function assumes that there are at least two elements in array. The function returns a negative value if the array is sorted in decreasing order and returns 0 if elements are equal */ int maxDiff(int arr[], int arr_size) { int max_diff = arr[1] - arr[0]; for (int i = 0; i < arr_size; i++) { for (int j = i+1; j < arr_size; j++) { if (arr[j] - arr[i] > max_diff) max_diff = arr[j] - arr[i]; } } return max_diff; } /* Driver program to test above function */ int main() { int arr[] = {1, 2, 90, 10, 110}; int n = sizeof(arr) / sizeof(arr[0]); // Function calling cout << "Maximum difference is " << maxDiff(arr, n); return 0; }
C
#include<stdio.h> /* The function assumes that there are at least two elements in array. The function returns a negative value if the array is sorted in decreasing order. Returns 0 if elements are equal */ int maxDiff(int arr[], int arr_size) { int max_diff = arr[1] - arr[0]; int i, j; for (i = 0; i < arr_size; i++) { for (j = i+1; j < arr_size; j++) { if (arr[j] - arr[i] > max_diff) max_diff = arr[j] - arr[i]; } } return max_diff; } /* Driver program to test above function */ int main() { int arr[] = {1, 2, 90, 10, 110}; printf("Maximum difference is %d", maxDiff(arr, 5)); getchar(); return 0; }
Java
// Java program to find Maximum difference // between two elements such that larger // element appears after the smaller number class MaximumDifference { /* The function assumes that there are at least two elements in array. The function returns a negative value if the array is sorted in decreasing order. Returns 0 if elements are equal */ int maxDiff(int arr[], int arr_size) { int max_diff = arr[1] - arr[0]; int i, j; for (i = 0; i < arr_size; i++) { for (j = i + 1; j < arr_size; j++) { if (arr[j] - arr[i] > max_diff) max_diff = arr[j] - arr[i]; } } return max_diff; } /* Driver program to test above functions */ public static void main(String[] args) { MaximumDifference maxdif = new MaximumDifference(); int arr[] = {1, 2, 90, 10, 110}; System.out.println("Maximum difference is " + maxdif.maxDiff(arr, 5)); } } // This code has been contributed by Mayank Jaiswal
Python3
# Python 3 code to find Maximum difference # between two elements such that larger # element appears after the smaller number # The function assumes that there are at # least two elements in array. The function # returns a negative value if the array is # sorted in decreasing order. Returns 0 # if elements are equal def maxDiff(arr, arr_size): max_diff = arr[1] - arr[0] for i in range( arr_size ): for j in range( i+1, arr_size ): if(arr[j] - arr[i] > max_diff): max_diff = arr[j] - arr[i] return max_diff # Driver program to test above function arr = [1, 2, 90, 10, 110] size = len(arr) print ("Maximum difference is", maxDiff(arr, size)) # This code is contributed by Swetank Modi
C#
// C# code to find Maximum difference using System; class GFG { // The function assumes that there // are at least two elements in array. // The function returns a negative // value if the array is sorted in // decreasing order. Returns 0 if // elements are equal static int maxDiff(int[] arr, int arr_size) { int max_diff = arr[1] - arr[0]; int i, j; for (i = 0; i < arr_size; i++) { for (j = i + 1; j < arr_size; j++) { if (arr[j] - arr[i] > max_diff) max_diff = arr[j] - arr[i]; } } return max_diff; } // Driver code public static void Main() { int[] arr = { 1, 2, 90, 10, 110 }; Console.Write("Maximum difference is " + maxDiff(arr, 5)); } } // This code is contributed by Sam007
PHP
<?php // PHP program to find Maximum difference // between two elements such that larger // element appears after the smaller number /* The function assumes that there are at least two elements in array. The function returns a negative value if the array is sorted in decreasing order and returns 0 if elements are equal */ function maxDiff($arr, $arr_size) { $max_diff = $arr[1] - $arr[0]; for ($i = 0; $i < $arr_size; $i++) { for ($j = $i+1; $j < $arr_size; $j++) { if ($arr[$j] - $arr[$i] > $max_diff) $max_diff = $arr[$j] - $arr[$i]; } } return $max_diff; } // Driver Code $arr = array(1, 2, 90, 10, 110); $n = sizeof($arr); // Function calling echo "Maximum difference is " . maxDiff($arr, $n); // This code is contributed // by Akanksha Rai(Abby_akku)
Javascript
<script> // javascript program to find Maximum difference // between two elements such that larger // element appears after the smaller number /* The function assumes that there are at least two elements in array. The function returns a negative value if the array is sorted in decreasing order and returns 0 if elements are equal */ function maxDiff( arr, arr_size) { let max_diff = arr[1] - arr[0]; for (let i = 0; i < arr_size; i++) { for (let j = i+1; j < arr_size; j++) { if (arr[j] - arr[i] > max_diff) max_diff = arr[j] - arr[i]; } } return max_diff; } // Driver program to test above function let arr = [1, 2, 90, 10, 110]; let n = arr.length; // Function calling document.write("Maximum difference is " + maxDiff(arr, n)); // This code is contributed by jana_sayantan. </script>
Producción :
Maximum difference is 109
Complejidad de tiempo: O(n^2)
Espacio auxiliar: O(1)
Método 2 (complicado y eficiente)
En este método, en lugar de tomar la diferencia del elemento seleccionado con todos los demás elementos, tomamos la diferencia con el elemento mínimo encontrado hasta el momento. Por lo tanto, debemos realizar un seguimiento de 2 cosas:
1) La diferencia máxima encontrada hasta ahora (max_diff).
2) Número mínimo visitado hasta el momento (min_element).
C++
// C++ program to find Maximum difference // between two elements such that larger // element appears after the smaller number #include <bits/stdc++.h> using namespace std; /* The function assumes that there are at least two elements in array. The function returns a negative value if the array is sorted in decreasing order and returns 0 if elements are equal */ int maxDiff(int arr[], int arr_size) { // Maximum difference found so far int max_diff = arr[1] - arr[0]; // Minimum number visited so far int min_element = arr[0]; for(int i = 1; i < arr_size; i++) { if (arr[i] - min_element > max_diff) max_diff = arr[i] - min_element; if (arr[i] < min_element) min_element = arr[i]; } return max_diff; } /* Driver program to test above function */ int main() { int arr[] = {1, 2, 90, 10, 110}; int n = sizeof(arr) / sizeof(arr[0]); // Function calling cout << "Maximum difference is " << maxDiff(arr, n); return 0; }
C
#include<stdio.h> /* The function assumes that there are at least two elements in array. The function returns a negative value if the array is sorted in decreasing order. Returns 0 if elements are equal */ int maxDiff(int arr[], int arr_size) { int max_diff = arr[1] - arr[0]; int min_element = arr[0]; int i; for(i = 1; i < arr_size; i++) { if (arr[i] - min_element > max_diff) max_diff = arr[i] - min_element; if (arr[i] < min_element) min_element = arr[i]; } return max_diff; } /* Driver program to test above function */ int main() { int arr[] = {1, 2, 6, 80, 100}; int size = sizeof(arr)/sizeof(arr[0]); printf("Maximum difference is %d", maxDiff(arr, size)); getchar(); return 0; }
Java
// Java program to find Maximum difference // between two elements such that larger // element appears after the smaller number class MaximumDifference { /* The function assumes that there are at least two elements in array. The function returns a negative value if the array is sorted in decreasing order. Returns 0 if elements are equal */ int maxDiff(int arr[], int arr_size) { int max_diff = arr[1] - arr[0]; int min_element = arr[0]; int i; for (i = 1; i < arr_size; i++) { if (arr[i] - min_element > max_diff) max_diff = arr[i] - min_element; if (arr[i] < min_element) min_element = arr[i]; } return max_diff; } /* Driver program to test above functions */ public static void main(String[] args) { MaximumDifference maxdif = new MaximumDifference(); int arr[] = {1, 2, 90, 10, 110}; int size = arr.length; System.out.println("MaximumDifference is " + maxdif.maxDiff(arr, size)); } } // This code has been contributed by Mayank Jaiswal
Python3
# Python 3 code to find Maximum difference # between two elements such that larger # element appears after the smaller number # The function assumes that there are # at least two elements in array. # The function returns a negative # value if the array is sorted in # decreasing order. Returns 0 if # elements are equal def maxDiff(arr, arr_size): max_diff = arr[1] - arr[0] min_element = arr[0] for i in range( 1, arr_size ): if (arr[i] - min_element > max_diff): max_diff = arr[i] - min_element if (arr[i] < min_element): min_element = arr[i] return max_diff # Driver program to test above function arr = [1, 2, 6, 80, 100] size = len(arr) print ("Maximum difference is", maxDiff(arr, size)) # This code is contributed by Swetank Modi
C#
// C# code to find Maximum difference using System; class GFG { // The function assumes that there // are at least two elements in array. // The function returns a negative // value if the array is sorted in // decreasing order.Returns 0 if // elements are equal static int maxDiff(int[] arr, int arr_size) { int max_diff = arr[1] - arr[0]; int min_element = arr[0]; int i; for (i = 1; i < arr_size; i++) { if (arr[i] - min_element > max_diff) max_diff = arr[i] - min_element; if (arr[i] < min_element) min_element = arr[i]; } return max_diff; } // Driver code public static void Main() { int[] arr = { 1, 2, 90, 10, 110 }; int size = arr.Length; Console.Write("MaximumDifference is " + maxDiff(arr, size)); } } // This code is contributed by Sam007
PHP
<?php // PHP program to find Maximum // difference between two elements // such that larger element appears // after the smaller number // The function assumes that there // are at least two elements in array. // The function returns a negative // value if the array is sorted in // decreasing order and returns 0 // if elements are equal function maxDiff($arr, $arr_size) { // Maximum difference found so far $max_diff = $arr[1] - $arr[0]; // Minimum number visited so far $min_element = $arr[0]; for($i = 1; $i < $arr_size; $i++) { if ($arr[$i] - $min_element > $max_diff) $max_diff = $arr[$i] - $min_element; if ($arr[$i] < $min_element) $min_element = $arr[$i]; } return $max_diff; } // Driver Code $arr = array(1, 2, 90, 10, 110); $n = count($arr); // Function calling echo "Maximum difference is " . maxDiff($arr, $n); // This code is contributed by Sam007 ?>
Javascript
<script> // Javascript code to find Maximum difference // between two elements such that larger // element appears after the smaller number // The function assumes that there // are at least two elements in array. // The function returns a negative // value if the array is sorted in // decreasing order.Returns 0 if // elements are equal function maxDiff(arr, arr_size) { let max_diff = arr[1] - arr[0]; let min_element = arr[0]; let i; for (i = 1; i < arr_size; i++) { if (arr[i] - min_element > max_diff) max_diff = arr[i] - min_element; if (arr[i] < min_element) min_element = arr[i]; } return max_diff; } let arr = [ 1, 2, 90, 10, 110 ]; let size = arr.length; document.write("Maximum difference is " + maxDiff(arr, size)); </script>
Producción:
Maximum difference is 109
Tiempo Complejidad : O(n)
Espacio Auxiliar : O(1)
Al igual que el elemento mínimo, también podemos realizar un seguimiento del elemento máximo desde el lado derecho. Gracias a Katamaran por sugerir este enfoque. A continuación se muestra la implementación:
C++
// C++ program to find Maximum difference // between two elements such that larger // element appears after the smaller number #include <bits/stdc++.h> using namespace std; /* The function assumes that there are at least two elements in array. The function returns a negative value if the array is sorted in decreasing order and returns 0 if elements are equal */ int maxDiff(int arr[], int n) { // Initialize Result int maxDiff = -1; // Initialize max element from right side int maxRight = arr[n-1]; for (int i = n-2; i >= 0; i--) { if (arr[i] > maxRight) maxRight = arr[i]; else { int diff = maxRight - arr[i]; if (diff > maxDiff) { maxDiff = diff; } } } return maxDiff; } /* Driver program to test above function */ int main() { int arr[] = {1, 2, 90, 10, 110}; int n = sizeof(arr) / sizeof(arr[0]); // Function calling cout << "Maximum difference is " << maxDiff(arr, n); return 0; }
Java
// Java program to find Maximum difference // between two elements such that larger // element appears after the smaller number import java.io.*; class GFG { /* The function assumes that there are at least two elements in array. The function returns a negative value if the array is sorted in decreasing order and returns 0 if elements are equal */ static int maxDiff(int arr[], int n) { // Initialize Result int maxDiff = -1; // Initialize max element from right side int maxRight = arr[n-1]; for (int i = n-2; i >= 0; i--) { if (arr[i] > maxRight) maxRight = arr[i]; else { int diff = maxRight - arr[i]; if (diff > maxDiff) { maxDiff = diff; } } } return maxDiff; } /* Driver program to test above function */ public static void main (String[] args) { int arr[] = {1, 2, 90, 10, 110}; int n = arr.length; // Function calling System.out.println ("Maximum difference is " + maxDiff(arr, n)); } //This code is contributed by Tushil.. }
Python3
# Python3 program to find Maximum difference # between two elements such that larger # element appears after the smaller number # The function assumes that there are # at least two elements in array. The # function returns a negative value if the # array is sorted in decreasing order and # returns 0 if elements are equal def maxDiff(arr, n): # Initialize Result maxDiff = -1 # Initialize max element from # right side maxRight = arr[-1] for i in reversed(arr[:-1]): if (i > maxRight): maxRight = i else: diff = maxRight - i if (diff > maxDiff): maxDiff = diff return maxDiff # Driver Code if __name__ == '__main__': arr = [1, 2, 90, 10, 110] n = len(arr) # Function calling print("Maximum difference is", maxDiff(arr, n)) # This code is contributed by 29AjayKumar
C#
// C# program to find Maximum difference // between two elements such that larger // element appears after the smaller number using System; class GFG { /* The function assumes that there are at least two elements in array. The function returns a negative value if the array is sorted in decreasing order and returns 0 if elements are equal */ static int maxDiff(int[] arr, int n) { // Initialize Result int maxDiff = -1; // Initialize max element from right side int maxRight = arr[n-1]; for (int i = n-2; i >= 0; i--) { if (arr[i] > maxRight) maxRight = arr[i]; else { int diff = maxRight - arr[i]; if (diff > maxDiff) { maxDiff = diff; } } } return maxDiff; } // Driver Code public static void Main () { int[] arr = {1, 2, 90, 10, 110}; int n = arr.Length; // Function calling Console.WriteLine("Maximum difference is " + maxDiff(arr, n)); } } // This code is contributed // by Akanksha Rai
PHP
<?php // PHP program to find Maximum difference // between two elements such that larger // element appears after the smaller number /* The function assumes that there are at least two elements in array. The function returns a negative value if the array is sorted in decreasing order and returns 0 if elements are equal */ function maxDiff($arr, $n) { // Initialize Result $maxDiff = -1; // Initialize max element from // right side $maxRight = $arr[$n - 1]; for ($i = $n - 2; $i >= 0; $i--) { if ($arr[$i] > $maxRight) $maxRight = $arr[$i]; else { $diff = $maxRight - $arr[$i]; if ($diff > $maxDiff) { $maxDiff = $diff; } } } return $maxDiff; } // Driver Code $arr = array(1, 2, 90, 10, 110); $n = sizeof($arr); // Function calling echo "Maximum difference is ", maxDiff($arr, $n); // This code is contributed by ajit ?>
Javascript
<script> // Javascript program to find Maximum difference // between two elements such that larger // element appears after the smaller number /* The function assumes that there are at least two elements in array. The function returns a negative value if the array is sorted in decreasing order and returns 0 if elements are equal */ function maxDiff(arr, n) { // Initialize Result let maxDiff = -1; // Initialize max element from right side let maxRight = arr[n-1]; for (let i = n-2; i >= 0; i--) { if (arr[i] > maxRight) maxRight = arr[i]; else { let diff = maxRight - arr[i]; if (diff > maxDiff) { maxDiff = diff; } } } return maxDiff; } let arr = [1, 2, 90, 10, 110]; let n = arr.length; // Function calling document.write("Maximum difference is " + maxDiff(arr, n)); </script>
Producción:
Maximum difference is 109
Tiempo Complejidad : O(n)
Espacio Auxiliar : O(1)
Método 3 (otra solución complicada)
Primero encuentre la diferencia entre los elementos adyacentes de la array y almacene todas las diferencias en una array auxiliar diff[] de tamaño n-1. Ahora, este problema se convierte en encontrar el subarreglo de suma máxima de este arreglo de diferencia. Gracias a Shubham Mittal por sugerir esta solución. A continuación se muestra la implementación:
C++
// C++ program to find Maximum difference // between two elements such that larger // element appears after the smaller number #include <bits/stdc++.h> using namespace std; /* The function assumes that there are at least two elements in array. The function returns a negative value if the array is sorted in decreasing order and returns 0 if elements are equal */ int maxDiff(int arr[], int n) { // Create a diff array of size n-1. // The array will hold the difference // of adjacent elements int diff[n-1]; for (int i=0; i < n-1; i++) diff[i] = arr[i+1] - arr[i]; // Now find the maximum sum // subarray in diff array int max_diff = diff[0]; for (int i=1; i<n-1; i++) { if (diff[i-1] > 0) diff[i] += diff[i-1]; if (max_diff < diff[i]) max_diff = diff[i]; } return max_diff; } /* Driver program to test above function */ int main() { int arr[] = {80, 2, 6, 3, 100}; int n = sizeof(arr) / sizeof(arr[0]); // Function calling cout << "Maximum difference is " << maxDiff(arr, n); return 0; }
C
#include<stdio.h> int maxDiff(int arr[], int n) { // Create a diff array of size n-1. The array will hold // the difference of adjacent elements int diff[n-1]; for (int i=0; i < n-1; i++) diff[i] = arr[i+1] - arr[i]; // Now find the maximum sum subarray in diff array int max_diff = diff[0]; for (int i=1; i<n-1; i++) { if (diff[i-1] > 0) diff[i] += diff[i-1]; if (max_diff < diff[i]) max_diff = diff[i]; } return max_diff; } /* Driver program to test above function */ int main() { int arr[] = {80, 2, 6, 3, 100}; int size = sizeof(arr)/sizeof(arr[0]); printf("Maximum difference is %d", maxDiff(arr, size)); return 0; }
Java
// Java program to find Maximum difference // between two elements such that larger // element appears after the smaller number class MaximumDifference { int maxDiff(int arr[], int n) { // Create a diff array of size n-1. The array will hold // the difference of adjacent elements int diff[] = new int[n - 1]; for (int i = 0; i < n - 1; i++) diff[i] = arr[i + 1] - arr[i]; // Now find the maximum sum subarray in diff array int max_diff = diff[0]; for (int i = 1; i < n - 1; i++) { if (diff[i - 1] > 0) diff[i] += diff[i - 1]; if (max_diff < diff[i]) max_diff = diff[i]; } return max_diff; } // Driver program to test above functions public static void main(String[] args) { MaximumDifference mxdif = new MaximumDifference(); int arr[] = {80, 2, 6, 3, 100}; int size = arr.length; System.out.println(mxdif.maxDiff(arr, size)); } } // This code has been contributed by Mayank Jaiswal
Python3
# Python 3 code to find Maximum difference # between two elements such that larger # element appears after the smaller number def maxDiff(arr, n): diff = [0] * (n - 1) for i in range (0, n-1): diff[i] = arr[i+1] - arr[i] # Now find the maximum sum # subarray in diff array max_diff = diff[0] for i in range(1, n-1): if (diff[i-1] > 0): diff[i] += diff[i-1] if (max_diff < diff[i]): max_diff = diff[i] return max_diff # Driver program to test above function arr = [80, 2, 6, 3, 100] size = len(arr) print ("Maximum difference is", maxDiff(arr, size)) # This code is contributed by Swetank Modi
C#
// C# code to find Maximum difference using System; class GFG { static int maxDiff(int[] arr, int n) { // Create a diff array of size n-1. // The array will hold the // difference of adjacent elements int[] diff = new int[n - 1]; for (int i = 0; i < n - 1; i++) diff[i] = arr[i + 1] - arr[i]; // Now find the maximum sum // subarray in diff array int max_diff = diff[0]; for (int i = 1; i < n - 1; i++) { if (diff[i - 1] > 0) diff[i] += diff[i - 1]; if (max_diff < diff[i]) max_diff = diff[i]; } return max_diff; } // Driver code public static void Main() { int[] arr = { 80, 2, 6, 3, 100 }; int size = arr.Length; Console.Write(maxDiff(arr, size)); } } // This code is contributed by Sam007
PHP
<?php // PHP program to find Maximum difference // between two elements such that larger // element appears after the smaller number /* The function assumes that there are at least two elements in array. The function returns a negative value if the array is sorted in decreasing order and returns 0 if elements are equal */ function maxDiff($arr, $n) { // Create a diff array of size n-1. // The array will hold the difference // of adjacent elements $diff[$n-1] = array(); for ($i=0; $i < $n-1; $i++) $diff[$i] = $arr[$i+1] - $arr[$i]; // Now find the maximum sum // subarray in diff array $max_diff = $diff[0]; for ($i=1; $i<$n-1; $i++) { if ($diff[$i-1] > 0) $diff[$i] += $diff[$i-1]; if ($max_diff < $diff[$i]) $max_diff = $diff[$i]; } return $max_diff; } // Driver Code $arr = array(80, 2, 6, 3, 100); $n = sizeof($arr); // Function calling echo "Maximum difference is " . maxDiff($arr, $n); // This code is contributed // by Akanksha Rai
Javascript
<script> // JavaScript program to find Maximum difference // between two elements such that larger // element appears after the smaller number /* The function assumes that there are at least two elements in array. The function returns a negative value if the array is sorted in decreasing order and returns 0 if elements are equal */ function maxDiff(arr, n) { // Create a diff array of size n-1. // The array will hold the difference // of adjacent elements let diff = new Array(n - 1); for(let i = 0; i < n - 1; i++) diff[i] = arr[i + 1] - arr[i]; // Now find the maximum sum // subarray in diff array let max_diff = diff[0]; for(let i = 1; i < n - 1; i++) { if (diff[i - 1] > 0) diff[i] += diff[i - 1]; if (max_diff < diff[i]) max_diff = diff[i]; } return max_diff; } // Driver code let arr = [ 80, 2, 6, 3, 100 ]; let n = arr.length; // Function calling document.write("Maximum difference is " + maxDiff(arr, n)); // This code is contributed by Mayank Tyagi </script>
Producción:
Maximum difference is 98
Tiempo Complejidad : O(n)
Espacio Auxiliar : O(n)
Podemos modificar el método anterior para que funcione en O(1) espacio adicional. En lugar de crear una array auxiliar, podemos calcular diff y max sum en el mismo ciclo. La siguiente es la versión optimizada para el espacio.
C++
// C++ program to find Maximum difference // between two elements such that larger // element appears after the smaller number #include <bits/stdc++.h> using namespace std; /* The function assumes that there are at least two elements in array. The function returns a negative value if the array is sorted in decreasing order and returns 0 if elements are equal */ int maxDiff (int arr[], int n) { // Initialize diff, current sum and max sum int diff = arr[1]-arr[0]; int curr_sum = diff; int max_sum = curr_sum; for(int i=1; i<n-1; i++) { // Calculate current diff diff = arr[i+1]-arr[i]; // Calculate current sum if (curr_sum > 0) curr_sum += diff; else curr_sum = diff; // Update max sum, if needed if (curr_sum > max_sum) max_sum = curr_sum; } return max_sum; } /* Driver program to test above function */ int main() { int arr[] = {80, 2, 6, 3, 100}; int n = sizeof(arr) / sizeof(arr[0]); // Function calling cout << "Maximum difference is " << maxDiff(arr, n); return 0; }
Java
// Java program to find Maximum // difference between two elements // such that larger element appears // after the smaller number class GFG { /* The function assumes that there are at least two elements in array. The function returns a negative value if the array is sorted in decreasing order and returns 0 if elements are equal */ static int maxDiff (int arr[], int n) { // Initialize diff, current // sum and max sum int diff = arr[1] - arr[0]; int curr_sum = diff; int max_sum = curr_sum; for(int i = 1; i < n - 1; i++) { // Calculate current diff diff = arr[i + 1] - arr[i]; // Calculate current sum if (curr_sum > 0) curr_sum += diff; else curr_sum = diff; // Update max sum, if needed if (curr_sum > max_sum) max_sum = curr_sum; } return max_sum; } // Driver Code public static void main(String[] args) { int arr[] = {80, 2, 6, 3, 100}; int n = arr.length; // Function calling System.out.print("Maximum difference is " + maxDiff(arr, n)); } } // This code is contributed by Smitha
Python3
# Python3 program to find Maximum difference # between two elements such that larger # element appears after the smaller number # The function assumes that there are # at least two elements in array. The # function returns a negative value if # the array is sorted in decreasing # order and returns 0 if elements are equal def maxDiff (arr, n): # Initialize diff, current # sum and max sum diff = arr[1] - arr[0] curr_sum = diff max_sum = curr_sum for i in range(1, n - 1): # Calculate current diff diff = arr[i + 1] - arr[i] # Calculate current sum if (curr_sum > 0): curr_sum += diff else: curr_sum = diff # Update max sum, if needed if (curr_sum > max_sum): max_sum = curr_sum return max_sum # Driver Code if __name__ == '__main__': arr = [80, 2, 6, 3, 100] n = len(arr) # Function calling print("Maximum difference is", maxDiff(arr, n)) # This code is contributed # by 29AjayKumar
C#
// C# program to find Maximum // difference between two elements // such that larger element appears // after the smaller number using System; class GFG { /* The function assumes that there are at least two elements in array. The function returns a negative value if the array is sorted in decreasing order and returns 0 if elements are equal */ static int maxDiff (int[] arr, int n) { // Initialize diff, current // sum and max sum int diff = arr[1] - arr[0]; int curr_sum = diff; int max_sum = curr_sum; for(int i = 1; i < n - 1; i++) { // Calculate current diff diff = arr[i + 1] - arr[i]; // Calculate current sum if (curr_sum > 0) curr_sum += diff; else curr_sum = diff; // Update max sum, if needed if (curr_sum > max_sum) max_sum = curr_sum; } return max_sum; } // Driver Code public static void Main() { int[] arr = {80, 2, 6, 3, 100}; int n = arr.Length; // Function calling Console.WriteLine("Maximum difference is " + maxDiff(arr, n)); } } // This code is contributed // by Akanksha Rai(Abby_akku)
PHP
<?php // PHP program to find Maximum difference // between two elements such that larger // element appears after the smaller number /* The function assumes that there are at least two elements in array. The function returns a negative value if the array is sorted in decreasing order and returns 0 if elements are equal */ function maxDiff ($arr, $n) { // Initialize diff, current sum // and max sum $diff = $arr[1] - $arr[0]; $curr_sum = $diff; $max_sum = $curr_sum; for($i = 1; $i < $n - 1; $i++) { // Calculate current diff $diff = $arr[$i + 1] - $arr[$i]; // Calculate current sum if ($curr_sum > 0) $curr_sum += $diff; else $curr_sum = $diff; // Update max sum, if needed if ($curr_sum > $max_sum) $max_sum = $curr_sum; } return $max_sum; } // Driver Code $arr = array(80, 2, 6, 3, 100); $n = sizeof($arr); // Function calling echo "Maximum difference is ", maxDiff($arr, $n); // This code is contributed // by Sach_code ?>
Javascript
<script> // Javascript program to find Maximum // difference between two elements // such that larger element appears // after the smaller number /* The function assumes that there are at least two elements in array. The function returns a negative value if the array is sorted in decreasing order and returns 0 if elements are equal */ function maxDiff (arr, n) { // Initialize diff, current // sum and max sum let diff = arr[1] - arr[0]; let curr_sum = diff; let max_sum = curr_sum; for(let i = 1; i < n - 1; i++) { // Calculate current diff diff = arr[i + 1] - arr[i]; // Calculate current sum if (curr_sum > 0) curr_sum += diff; else curr_sum = diff; // Update max sum, if needed if (curr_sum > max_sum) max_sum = curr_sum; } return max_sum; } // Driver Code let arr = [ 80, 2, 6, 3, 100 ]; let n = arr.length; // Function calling document.write("Maximum difference is " + maxDiff(arr, n)); // This code is contributed by rag2127 </script>
Producción:
Maximum difference is 98
Tiempo Complejidad : O(n)
Espacio Auxiliar : O(1)
A continuación se muestra una variación de este problema:
Diferencia máxima de la suma de elementos en dos filas en una array
Escriba comentarios si encuentra algún error en los códigos/algoritmos anteriores, o encuentre otras formas de resolver el mismo problema
Publicación traducida automáticamente
Artículo escrito por GeeksforGeeks-1 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA