Kadane's Algorithm implementation in java
Code::
import java.util.*;
class Test
{
public static void main(String[] args){
int[] arr = {1,2,3,-2,5};
int maxSum = arr[0];
int currSum = 0;
for(int i=0;i<arr.length;i++){
currSum += arr[i];
if(currSum > maxSum){
maxSum = currSum;
}
if(currSum<0){
currSum = 0;
}
}
System.out.println(maxSum);
}
}
o/p: 9
Largest Sum Contiguous Subarray
Brute Force
Code:
import java.util.*;
class Test
{
public static void main(String[] args){
int[] arr = {1,2,3,-2,5};
int max = Integer.MIN_VALUE;
for(int i=0;i<arr.length;i++){
int sum = arr[i];
max = Math.max(sum,max);
for(int j=i+1;j<arr.length;j++){
sum = sum + arr[j];
max = Math.max(sum,max);
}
}
System.out.println(max);
}
}
Comments
Post a Comment