forked from theprogrammedwords/Algorithm-Solutions-Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMaxSumPartialMethod.java
More file actions
32 lines (27 loc) · 839 Bytes
/
MaxSumPartialMethod.java
File metadata and controls
32 lines (27 loc) · 839 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
30
31
32
//Maximum sum calculation in an array using partial sum method
public class MaxSumPartialMethod {
static int Nmax = 1001;
static int[] a = new int[Nmax];
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
for(int i=1; i<=n; i++)
a[i] = sc.nextInt();
System.out.println(maxSum(a,n));
}
public static int maxSum(int a[], int n){
int[] s = new int[Nmax];
int ans = a[1];
int minS = 0;
s[1] = a[1];
for(int i=2; i<=n;i++)
s[i] += s[i-1]+a[i];
for(int i=1; i<=n;i++){
if(s[i]-minS > ans)
ans = s[i] - minS;
if(s[i] < minS)
minS = s[i];
}
return ans;
}
}