Maximum sum subarray
package datastrusture;
public class MaximumSumSubArray {
// efficient solution
private static int maxEnding(int[] arr, int index) {
if(index == 0){
return arr[0];
}
int a;
return a = Math.max(maxEnding(arr,index - 1) + arr[index], arr[index]);
}
public static int getMaximum(int[] arr) {
int n = arr.length;
int res = arr[0];
int current;
for(int i = 0; i < n; i++){
current = maxEnding(arr, i);
res = Math.max(res, current);
}
return res;
}
// First approach of mine NAIVE SOLUTION
public static int maximum(int[] arr){
int n = arr.length;
// int min = 0;
// int sum = 0;
// int max = arr[0];
int max1 = arr[0];
// for(int i = 0; i < n; i++){
// sum = sum + arr[i];
// min = Math.min(min, arr[i]);
// max = Math.max(max,arr[i]);
// }
// if(min >= 0){
// return sum;
// }
// if(max < 0){
// return max;
// }
for(int i = 0; i < n; i++){
int sum1 = 0;
for(int j = i; j < n; j++) {
sum1 = sum1 + arr[j];
max1 = Math.max(sum1, max1);
}
}
return max1;
}
public static void main(String[] args) {
int[] array = {2,3,-8,7,-1,2,-3};
System.out.println(getMaximum(array));
}
}
Comments
Post a Comment