-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmax_non_negative_subarray_sum.java
85 lines (73 loc) · 2.01 KB
/
max_non_negative_subarray_sum.java
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author shivam
*/
public class maxNonNegativeSubarray {
public static void main(String[] args) {
int arr[]={1,95,5,-7,6,-2,8,78,-4,5,6,7,112};
int neg_index[]= new int[arr.length];
int index=0;
int sum=0,max_sum=-500;
int m_start=-1, m_end=-1;
//storing negative index
for(int i=0;i<arr.length;i++)
{
if(arr[i]<0)
{
neg_index[index++]=i; // 3_6_8,
}
}
for(int i=0;i<index;i++)
{
System.out.print(neg_index[i]+" ");
}
System.out.println("");
int itr=0,itr1=1;
while(itr1<index)
{
for(int j=neg_index[itr]+1;j<neg_index[itr1];j++)
{
sum+=arr[j];
}
if(sum>max_sum)
{
max_sum=sum;
m_start=neg_index[itr]+1;
m_end=neg_index[itr1]-1;
}
sum=0;
itr++;
itr1++;
}
//check for 0 to first negative index
sum=0;
for(int j=0;j<neg_index[0];j++)
{
sum+=arr[j];
}
if(sum>max_sum)
{
max_sum=sum;
m_start=0;
m_end=neg_index[0]-1;
}
//check for last negative index to array end
sum=0;
for(int j=neg_index[index-1]+1;j<arr.length;j++)
{
sum+=arr[j];
}
if(sum>max_sum)
{
max_sum=sum;
m_start=neg_index[index-1]+1;
m_end=arr.length-1;
}
System.out.println("inclusive start index "+m_start+"::inclusive end index::"+m_end+":: max sum is:: "+max_sum);
}
}