0% found this document useful (0 votes)
20 views

Max Subarray

This document discusses three algorithms for finding the maximum sum of a subarray: brute force with O(n^3) time complexity, prefix sum with O(n^2) time complexity, and Kadane's algorithm with optimal O(n) time complexity. It provides code implementations in Java for each algorithm. Kadane's algorithm works by tracking the maximum sum seen so far in a single pass of the array and resetting the sum to 0 if it becomes negative to avoid including negative numbers.

Uploaded by

Jaishree Chakare
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

Max Subarray

This document discusses three algorithms for finding the maximum sum of a subarray: brute force with O(n^3) time complexity, prefix sum with O(n^2) time complexity, and Kadane's algorithm with optimal O(n) time complexity. It provides code implementations in Java for each algorithm. Kadane's algorithm works by tracking the maximum sum seen so far in a single pass of the array and resetting the sum to 0 if it becomes negative to avoid including negative numbers.

Uploaded by

Jaishree Chakare
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

Finding max of subarray

29 September 2022 17:58

BRUTE FORCE

import java.util.*;
public class Javabasics{
public static void max_sum(int A[]){
int large=Integer.MIN_VALUE;
int start,end,sum=0;
for(int i=0;i<A.length;i++){
start=i;
for(int j=i;j<A.length;j++){
end=j;
for(int k=start;k<=end;k++){ //tc = big_o(n^3)
sum+=A[k];
}
if(sum>large){
large=sum;
}
sum=0;
}
}
System.out.println(large);
}
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
int A[] = new int[5];
for(int i=0;i<A.length;i++){
A[i]=sc.nextInt();
}
max_sum(A);
}
}

PREFIX SUM

import java.util.*;
public class Javabasics{
public static void max_sum(int A[],int P[]){
int large=Integer.MIN_VALUE;
int start,end,sum=0;
for(int i=0;i<A.length;i++){
start=i;
for(int j=i;j<A.length;j++){
end=j;
sum=(start==0)? P[end] : P[end]-P[start-1]; //tc = big_o(n^
2);
if(sum>large){
large=sum;
}
}
}
System.out.println(large);
}
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
int A[] = new int[5];
int P[] = new int[A.length];
for(int i=0;i<A.length;i++){
A[i]=sc.nextInt();
}
P[0]=A[0];
for(int i=1;i<P.length;i++){
P[i]=P[i-1]+A[i];
}
max_sum(A,P);
}
}

KADANES ALGORITHM

import java.util.*;
public class Javabasics{
public static void max_sum(int A[]){
int sum=0;
int large = Integer.MIN_VALUE;
for(int i=0;i<A.length;i++){
sum+=A[i];
if(sum<0){ //tc =
big_o(n);
sum=0;
}
if(sum>large){
large=sum;
}
}
System.out.println(large);
}
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
int A[] = new int[5];
for(int i=0;i<A.length;i++){
A[i]=sc.nextInt();
}
max_sum(A);
}
}

You might also like