-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLC689.java
More file actions
107 lines (84 loc) · 2.88 KB
/
LC689.java
File metadata and controls
107 lines (84 loc) · 2.88 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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
/*
* LC689
*/
import java.util.*;
public class LC689 {
private static int[] prefixSum;
private static int[][] mem;
// Helper function to find the max sum
private static int findMaxSum(int[] nums, int pos, int count, int k) {
// Base Cases
if (count == 3) {
return 0;
}
if (pos > nums.length - k) {
return 0;
}
if (mem[pos][count] != -1) {
return mem[pos][count];
}
// Don't start sub array here
int dontStart = findMaxSum(nums, pos + 1, count, k);
// Start sub array here
int startHere = findMaxSum(nums, pos + k, count + 1, k) + prefixSum[pos + k] - prefixSum[pos];
return mem[pos][count] = Math.max(dontStart, startHere);
}
// Helper function to find path of the Max Sum
private static void findMaxSumPath(int[] nums, int pos, int count, int k, int[] path, int pathIndex) {
// Base case
if (count == 3) {
return;
}
if (pos > nums.length - k) {
return;
}
// Don't start sub array here
int dontStart = findMaxSum(nums, pos + 1, count, k);
// Start sub array here
int startHere = findMaxSum(nums, pos + k, count + 1, k) + prefixSum[pos + k] - prefixSum[pos];
// Chose optimal path
if (startHere >= dontStart) {
path[pathIndex] = pos;
findMaxSumPath(nums, pos + k, count + 1, k, path, pathIndex + 1); // Include pos
} else {
findMaxSumPath(nums, pos + 1, count, k, path, pathIndex); // Don't include pos
}
}
public static int[] maxSumOfThreeSubarrays(int[] nums, int k) {
int n = nums.length;
mem = new int[n][3];
for (int[] row : mem) {
Arrays.fill(row, -1);
}
prefixSum = new int[n + 1];
for (int i = 0; i < n; i++) {
prefixSum[i + 1] = prefixSum[i] + nums[i];
}
findMaxSum(nums, 0, 0, k);
int[] path = new int[3];
findMaxSumPath(nums, 0, 0, k, path, 0);
return path;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter The Nums Array Size : ");
int n = sc.nextInt();
System.out.println();
int[] nums = new int[n];
System.out.println("Enter The Nums Array Element : ");
for (int i = 0; i < nums.length; i++) {
System.out.printf("%d : ", i);
nums[i] = sc.nextInt();
}
System.out.println();
System.out.print("Enter The K-Value : ");
int k = sc.nextInt();
System.out.println();
int[] ans = maxSumOfThreeSubarrays(nums, k);
System.out.println("Answer : ");
for (int i = 0; i < ans.length; i++) {
System.out.printf("%d ", ans[i]);
}
sc.close();
}
}