Last active
September 26, 2019 15:33
-
-
Save criskgl/d5d079066b352a63474cbf7a48e7516a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class MaxSubArraySum { | |
public static void main(String[] args) { | |
// TODO Auto-generated method stub | |
int[] a = {1, -3, 2, 1,-1}; | |
int result = maxSumSubarray(a); | |
System.out.println(result); | |
} | |
public static int maxSumSubarray(int[] A){ | |
int n = A.length; | |
int local_max = 0; | |
int global_max = Integer.MIN_VALUE; | |
for(int i = 0; i < n; i++){ | |
/* | |
* Tenemos que terminar si el elemento por si slo mejora el resultado o no | |
* al sumarse a a suma de los elementos que venían por detrás(local_max). | |
* Si mejorase el resultado se ese eelemento evaluado se convertiria en local_max | |
* Si no lo mejorase se uniria a los de detraás reescribiendo el local_max a lo que | |
* había en local_max por lo que había en local_max más el elemento evaluado | |
*/ | |
int current = A[i]; | |
local_max = Math.max(current, current + local_max); | |
if(local_max > global_max){ | |
global_max = local_max; | |
} | |
} | |
return global_max; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment