-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathMaximumSubArray-02.java
More file actions
29 lines (28 loc) · 852 Bytes
/
MaximumSubArray-02.java
File metadata and controls
29 lines (28 loc) · 852 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#Calculate sum upto each index in index of a different array & then calculate the sum upto any index by formula:
#current_sum = sum[j] - sum[i] + array[i];
public class LargestSubArray
{
public static void main(String[] args)
{
int array[] = {-1, 2, -1, 4, 5};
int max = Integer.MIN_VALUE;
int sum[] = new int[array.length];
sum[0] = array[0];
for (int i = 1; i < sum.length; i++)
{
sum[i] = sum[i-1] + array[i];
}
for(int i = 0; i < array.length; i++)
{
for(int j=i; j<array.length; j++)
{
int cursum = sum[j] - sum[i] + array[i];
if(cursum > max)
{
max = cursum;
}
}
}
System.out.println("maximum is : "+max);
}
}