-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCherry_Pickup_II.java
More file actions
116 lines (111 loc) · 3.25 KB
/
Cherry_Pickup_II.java
File metadata and controls
116 lines (111 loc) · 3.25 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
108
109
110
111
112
113
114
115
116
import java.util.*;
import java.io.*;
import java.lang.*;
public class Cherry_Pickup_II {
// Dp Memoization
class Solution {
public int cherryPickup(int[][] grid) {
int nrow = grid.length;
int ncol = grid[0].length;
int[][][] dp = new int[nrow][ncol][ncol];
for(int[][] rows : dp)
{
for(int[] rows1 : rows)
{
Arrays.fill(rows1 , -1);
}
}
return fun(nrow , ncol , 0 , 0 , ncol-1 , grid , dp);
}
public static int fun(int nrow , int ncol , int r , int c1 , int c2 , int[][] grid , int[][][] dp)
{
if(c1<0 || c2<0 || c1>=ncol || c2>=ncol)
{
return 0;
}
if(r >= nrow-1)
{
if(c1==c2)
{
return grid[r][c1];
}
else
{
return grid[r][c1] + grid[r][c2];
}
}
if(dp[r][c1][c2] != -1)
{
return dp[r][c1][c2];
}
int max_cherry = 0;
for(int i = -1 ; i<=1 ; i++)
{
for(int j = -1 ; j<=1 ; j++)
{
int cherry;
if(c1==c2)
{
cherry = grid[r][c1] + fun(nrow , ncol , r+1 , c1+i , c2+j , grid , dp);
}
else
{
cherry = grid[r][c1] + grid[r][c2] + fun(nrow , ncol , r+1 , c1+i , c2+j , grid , dp);
}
if(max_cherry<cherry)
{
max_cherry = cherry;
}
}
}
return dp[r][c1][c2] = max_cherry;
}
}
//Recurssion
// class Solution {
// public int cherryPickup(int[][] grid) {
// int nrow = grid.length;
// int ncol = grid[0].length;
// return fun(nrow , ncol , 0 , 0 , ncol-1 , grid);
// }
// public static int fun(int nrow , int ncol , int r , int c1 , int c2 , int[][] grid)
// {
// if(c1<0 || c2<0 || c1>=ncol || c2>=ncol)
// {
// return 0;
// }
// if(r >= nrow-1)
// {
// if(c1==c2)
// {
// return grid[r][c1];
// }
// else
// {
// return grid[r][c1] + grid[r][c2];
// }
// }
// int max_cherry = 0;
// for(int i = -1 ; i<=1 ; i++)
// {
// for(int j = -1 ; j<=1 ; j++)
// {
// int cherry;
// if(c1==c2)
// {
// cherry = grid[r][c1] + fun(nrow , ncol , r+1 , c1+i , c2+j , grid);
// }
// else
// {
// cherry = grid[r][c1] + grid[r][c2] + fun(nrow , ncol , r+1 , c1+i , c2+j , grid);
// }
// if(max_cherry<cherry)
// {
// max_cherry = cherry;
// }
// }
// }
// return max_cherry;
// }
// }
}