-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution.cs
More file actions
52 lines (48 loc) · 1.33 KB
/
Solution.cs
File metadata and controls
52 lines (48 loc) · 1.33 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
public class Solution
{
public int MaxCollectedFruits(int[][] fruits)
{
int n = fruits.Length;
int ans = 0;
for (int i = 0; i < n; i++)
{
ans += fruits[i][i];
}
int dp()
{
int[] prev = new int[n];
Array.Fill(prev, int.MinValue);
int[] curr = new int[n];
prev[n - 1] = fruits[0][n - 1];
for (int i = 1; i < n - 1; ++i)
{
Array.Fill(curr, int.MinValue);
for (int j = Math.Max(n - 1 - i, i + 1); j < n; ++j)
{
int best = prev[j];
if (j - 1 >= 0)
{
best = Math.Max(best, prev[j - 1]);
}
if (j + 1 < n)
{
best = Math.Max(best, prev[j + 1]);
}
curr[j] = best + fruits[i][j];
}
(curr, prev) = (prev, curr);
}
return prev[n - 1];
}
ans += dp();
for (int i = 0; i < n; ++i)
{
for (int j = 0; j < i; ++j)
{
(fruits[i][j], fruits[j][i]) = (fruits[j][i], fruits[i][j]);
}
}
ans += dp();
return ans;
}
}