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
|
public class Solution {
public int[] maxMinSumMemoized(int[] nums, int M) {
int n = nums.length;
Map<Integer, int[]> memo = new HashMap<>();
int max_sum = Integer.MIN_VALUE;
int min_sum = Integer.MAX_VALUE;
for (int i = 0; i < n; i++) {
int[] result = dfs(nums, i, M, memo);
max_sum = Math.max(max_sum, result[0]);
min_sum = Math.min(min_sum, result[1]);
}
return new int[] {max_sum, min_sum};
}
private int[] dfs(int[] nums, int i, int M, Map<Integer, int[]> memo) {
if (i < 0) {
return new int[] {Integer.MIN_VALUE, Integer.MAX_VALUE};
}
if (i <= M) {
return new int[] {nums[i], nums[i]};
}
if (memo.containsKey(i)) {
return memo.get(i);
}
int[] result = dfs(nums, i - M - 1, M, memo);
int max_without_i = result[0];
int min_without_i = result[1];
int max_with_i = Math.max(nums[i], nums[i] + max_without_i);
int min_with_i = Math.min(nums[i], nums[i] + min_without_i);
memo.put(i, new int[] {max_with_i, min_with_i});
return memo.get(i);
}
}
|