Skip to content

Commit a3bde97

Browse files
authoredSep 4, 2023
Create random.java
1 parent a1da0ab commit a3bde97

File tree

1 file changed

+73
-0
lines changed

1 file changed

+73
-0
lines changed
 

‎random.java

+73
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
2+
public static boolean isSafe(int[][] mat, int i, int j) {
3+
if (i < 0 || i >= mat.length || j < 0 || j >= mat[0].length || mat[i][j] == -1) {
4+
return false;
5+
}
6+
7+
return true;
8+
}
9+
10+
public static int findMaximum(int[][] mat, List<Integer> indices, HashMap<List<Integer>, Integer> cache) {
11+
int i1 = indices.get(0), j1 = indices.get(1), i2 = indices.get(2), j2 = indices.get(3);
12+
if (!isSafe(mat, i1, j1) || (!isSafe(mat, i2, j2))) {
13+
return Integer.MIN_VALUE;
14+
}
15+
16+
List<Integer> lastIndex = Arrays.asList(mat.length-1, mat[0].length-1, mat.length-1, mat[0].length-1);
17+
if (indices.equals(lastIndex)) {
18+
return mat[i1][j1];
19+
}
20+
21+
Integer value = cache.get(indices);
22+
if (value != null) {
23+
return value;
24+
}
25+
26+
Integer numPoints = mat[i1][j1];
27+
if (i1 != i2 || j1 != j2) {
28+
numPoints += mat[i2][j2];
29+
}
30+
numPoints += Math.max(
31+
Math.max(findMaximum(mat, Arrays.asList(i1+1, j1, i2+1, j2), cache),
32+
findMaximum(mat, Arrays.asList(i1, j1+1, i2, j2+1), cache)),
33+
Math.max(findMaximum(mat, Arrays.asList(i1+1, j1, i2, j2+1), cache),
34+
findMaximum(mat, Arrays.asList(i1, j1+1, i2+1, j2), cache))
35+
);
36+
cache.put(indices, numPoints);
37+
38+
return numPoints;
39+
}
40+
public static int GetMaxMangoes(List<String> a) {
41+
int n = a.size();
42+
int m = a.get(0).length();
43+
44+
int[][] mat = new int[n][m];
45+
46+
for(int i = 0; i < n; i++) {
47+
for(int j = 0; j < m; j++) {
48+
if(a.get(i).charAt(j) == '*') {
49+
mat[i][j] = 0;
50+
} else if(a.get(i).charAt(j) == '$') {
51+
mat[i][j] = 1;
52+
} else {
53+
mat[i][j] = -1;
54+
}
55+
}
56+
}
57+
58+
HashMap<List<Integer>, Integer> cache = new HashMap<List<Integer>, Integer>();
59+
int ans = findMaximum(mat, Arrays.asList(0, 0, 0, 0), cache);
60+
61+
cache = new HashMap<>();
62+
63+
int[][] b = new int[n][m];
64+
65+
for(int j = n-1; j >= 0; j--) {
66+
for(int i = 0; i < n; i++) {
67+
b[n-1-i][n-1-j] = mat[i][j];
68+
}
69+
}
70+
71+
ans += findMaximum(b, Arrays.asList(0,0,0,0), cache);
72+
return ans;
73+
}

0 commit comments

Comments
 (0)
Please sign in to comment.