-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathkconcat.java
More file actions
84 lines (56 loc) · 1.72 KB
/
Copy pathkconcat.java
File metadata and controls
84 lines (56 loc) · 1.72 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
75
76
77
78
79
80
81
82
83
84
package revision;
import java.util.Scanner;
class Codechef {
public static long kadane(long arr[]) {
int n = arr.length;
long cs = 0, mx = Integer.MIN_VALUE;
for (int i = 0; i < n; i++) {
cs += arr[i];
if (cs < 0)
cs = 0;
else
mx = Math.max(mx, cs);
}
return mx;
}
public static long accumulate(long arr[]) {
long sum = 0;
for (int i = 0; i < arr.length; i++) {
sum += arr[i];
}
return sum;
}
public static void main(String[] args) throws java.lang.Exception {
int t;
Scanner sc = new Scanner(System.in);
t = sc.nextInt();
while (t-- > 0) {
int n, k;
n = sc.nextInt();
k = sc.nextInt();
long arr[] = new long[n];
for (int i = 0; i < n; i++) {
arr[i] = sc.nextLong();
}
long maxsum = kadane(arr);
if (k == 1) {
System.out.println(maxsum);
} else {
long total = accumulate(arr);
long prefix = 0, suffix = 0, p = 0, s = 0;
for (int i = 0; i < n; i++) {
p += arr[i];
s += arr[n - i - 1];
prefix = Math.max(prefix, p);
suffix = Math.max(suffix, s);
}
if (total > 0) {
maxsum = Math.max((((k - 2) * total) + prefix + suffix), maxsum);
System.out.println(maxsum);
} else {
System.out.println(prefix + suffix);
}
}
}
}
}