-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathletcode-q-1.java
More file actions
70 lines (56 loc) · 1.74 KB
/
letcode-q-1.java
File metadata and controls
70 lines (56 loc) · 1.74 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
class Solution {
int dp[][];
public int maxCollectedFruits(int[][] fruits) {
int n = fruits.length;
dp = new int[n][n];
for (int i = 0; i < n; i++) {
Arrays.fill(dp[i], -1);
}
int ans = 0;
return child1(fruits) + child2(fruits, 0, n - 1, n) + child3(fruits, n - 1, 0, n);
}
int child1(int[][] fruits) {
int ans = 0;
for (int i = 0; i < fruits.length; i++) {
ans += fruits[i][i];
fruits[i][i] = 0;
}
return ans;
}
int child2(int[][] fruits, int i, int j, int n) {
if (i >= n || i < 0 || j >= n || j < 0) {
return 0;
}
if (i > j || i == j) {
return 0;
}
if (i == n - 1 && j == n - 1) {
return 0;
}
if (dp[i][j] != -1) {
return dp[i][j];
}
int a = fruits[i][j] + child2(fruits, i + 1, j, n);
int b = fruits[i][j] + child2(fruits, i + 1, j + 1, n);
int c = fruits[i][j] + child2(fruits, i + 1, j - 1, n);
return dp[i][j] = Math.max(Math.max(a, b), c);
}
int child3(int[][] fruits, int i, int j, int n) {
if (i >= n || i < 0 || j >= n || j < 0) {
return 0;
}
if (j > i || i == j) {
return 0;
}
if (i == n - 1 && j == n - 1) {
return 0;
}
if (dp[i][j] != -1) {
return dp[i][j];
}
int right = fruits[i][j] + child3(fruits, i, j + 1, n);
int rightUp = fruits[i][j] + child3(fruits, i - 1, j + 1, n);
int rightDown = fruits[i][j] + child3(fruits, i + 1, j + 1, n);
return dp[i][j] = Math.max(Math.max(right, rightUp), rightDown);
}
}