-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgoldmine.java
58 lines (45 loc) · 2.05 KB
/
goldmine.java
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
/*
1. You are given a number n, representing the number of rows.
2. You are given a number m, representing the number of columns.
3. You are given n*m numbers, representing elements of 2d array a, which represents a gold mine.
4. You are standing in front of left wall and are supposed to dig to the right wall. You can start from
any row in the left wall.
5. You are allowed to move 1 cell right-up (d1), 1 cell right (d2) or 1 cell right-down(d3).
<img src="http://pepcoding.com/resources/ojquestionresource/images/goldmine.JPEG" alt="goldmine">
6. Each cell has a value that is the amount of gold available in the cell.
7. You are required to identify the maximum amount of gold that can be dug out from the mine.*/
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
int m = Integer.parseInt(br.readLine());
int[][] arr = new int[n][m];
for (int i = 0; i < n; i++) {
String str = br.readLine();
for (int j = 0; j < m; j++) {
arr[i][j] = Integer.parseInt(str.split(" ")[j]);
}
}
int[][] dp = new int[arr.length][arr[0].length];
for (int j = arr[0].length - 1; j >= 0; j--) {
for (int i = arr.length - 1; i >= 0; i--) {
if (j == arr[0].length - 1) {
dp[i][j] = arr[i][j];
} else if (i == arr.length - 1) {
dp[i][j] = arr[i][j] + Math.max(dp[i][j + 1], dp[i - 1][j + 1]);
} else if (i == 0) {
dp[i][j] = arr[i][j] + Math.max(dp[i][j + 1], dp[i + 1][j + 1]);
} else {
dp[i][j] = arr[i][j] + Math.max(dp[i][j + 1], Math.max(dp[i + 1][j + 1], dp[i - 1][j + 1]));
}
}
}
int max = dp[0][0];
for (int i = 1; i < dp.length; i++) {
max = Math.max(max, dp[i][0]);
}
System.out.println(max);
}
}