forked from theprogrammedwords/Algorithm-Solutions-Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPickLargestSum.java
More file actions
74 lines (58 loc) · 1.61 KB
/
PickLargestSum.java
File metadata and controls
74 lines (58 loc) · 1.61 KB
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
/*Problem Description
You are given an Array A of size N. You have to pick total B elements from either left or right end of the array A to get the maximum sum.
Input format
First line will contain two space separated integers N and B respectively.
Second line will contain N space separated integers array A.
Output format
Print the answer in a single line.
Sample Input 1
5 4
4 -3 1 2 1
Sample Output 1
8
Explanation
4 + 1 + 2 + 1 = 8
We will have the maximum sum for one element from the first side and three elements from the back.
Constraints
1<=N<=1000000
-1000000<=Ai<=1000000
0<=B<=N
*/
import java.util.*;
class PickLargestSum{
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
int B = sc.nextInt();
List<Integer> A = new ArrayList<Integer>();
for (int i = 0; i < N; i++) {
A.add(sc.nextInt());
}
long result = pickLargestSum(N, B, A);
System.out.println(result);
sc.close();
}
static long pickLargestSum(int N, int B, List<Integer>A){
long sum1 = 0L;
long sum2 = 0L;
long min1;
for(int i=0; i<A.size(); i++){
sum1 += (long) A.get(i);
}
int i=0;
int j = N-B-1;
for(int k=i; k<=j; k++){
sum2 += (long) A.get(k);
}
min1 = (long) sum2;
i++;
j++;
while(j<A.size()){
sum2+= (long) A.get(j) - A.get(i-1);
min1 = Math.min(sum2, min1);
i++;
j++;
}
return (sum1-min1);
}
}