
You are an explorer on an expedition to collect rare rocks. You are given a 2D grid of size m x n, where each cell grid[i][j] represents a city containing a certain number of these rocks.
Your journey must start at the bottom-left corner (grid[m-1][0]) and end at the top-right corner (grid[0][n-1]). From any city (i, j), you are only allowed to move to the city directly up (i-1, j) or to the city directly right (i, j+1). You cannot move outside the grid boundaries.
The total number of rocks you collect is the sum of the rocks in every city you visit, including the starting and ending cities. Your task is to find a path that maximizes the total number of rocks collected.
Return the maximum number of rocks you can collect.
The first line contains two space-separated integers, m and n, representing the number of rows and columns in the grid.
The next m lines each contain n space-separated integers, representing the grid.
Print a single integer representing the maximum number of rocks that can be collected.
A simple greedy approach (always moving to the adjacent city with more rocks) may not yield the optimal overall path. This problem has optimal substructure and overlapping subproblems, making it a great candidate for dynamic programming.
3 3
1 2 3
4 8 2
1 5 3
19
The optimal path is (2,0) -> (2,1) -> (1,1) -> (1,2) -> (0,2).
The total number of rocks collected is 1 + 5 + 8 + 2 + 3 = 19.
3 3
1 1 100
1 10 1
20 1 1
123
The optimal path is (2,0) -> (2,1) -> (2,2) -> (1,2) -> (0,2).
The total number of rocks collected is 20 + 1 + 1 + 1 + 100 = 123. A greedy path starting with (2,0) -> (1,0) (value 1) instead of (2,0) -> (2,1) (value 1) would lead to a suboptimal total.
The expected time complexity is O(m*n).
1 <= m, n <= 200
0 <= grid[i][j] <= 1000
Time Limit: 1 sec