Skip to content

Commit 665a38e

Browse files
committed
Added a 2-D DP problem of traversing through a 2-D array
Fixes matthewsamuel95#2
1 parent 77c202a commit 665a38e

File tree

2 files changed

+98
-0
lines changed

2 files changed

+98
-0
lines changed
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
#include <stdio.h>
2+
3+
int m,n;
4+
5+
int max(int a,int b)
6+
{
7+
return a>b?a:b;
8+
}
9+
10+
void coin_sort(int arr[][n])
11+
{
12+
for(int i=1;i<m;i++)
13+
arr[i][0] += arr[i-1][0];
14+
15+
for(int j=1;j<n;j++)
16+
arr[0][j] += arr[0][j-1];
17+
18+
for(int i=1;i<m;i++)
19+
{
20+
for(int j=1;j<n;j++)
21+
{
22+
arr[i][j] += max(arr[i-1][j],arr[i][j-1]);
23+
}
24+
}
25+
}
26+
27+
int main()
28+
{
29+
int t;
30+
scanf("%d", &t);
31+
while(t--)
32+
{
33+
scanf("%d %d",&m,&n);
34+
int arr[m][n];
35+
for(int i=0;i<m;i++)
36+
for(int j=0;j<n;j++)
37+
scanf("%d",&arr[i][j]);
38+
39+
coin_sort(arr);
40+
41+
printf("%d\n",arr[m-1][n-1]);
42+
}
43+
return 0;
44+
}
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
# Problem Statement#1
2+
You have a friend named Shivam and he is going to school from his house. He finds out that there are coins scattered on the roads and since he is greedy he wants to collect them all but since he doesn't want to be late for school, he decides to collect as many as he can on his way. He is a student and knows math so he figures he could travel the path in the form of a 2-D grid.
3+
4+
Assume the whole space to be a 2-D block of **MxN** boxes and in each box there are some or no coins, Shivam's house is on the **Top-Left corner** and school is at the **Bottom-Right corner**. Due to his shortage of time he can travel either one step(box) **Right** or **Down** towards the school and collect the coins he find on his way.
5+
6+
Since there are multiple paths possible, he can't figure out which path will yield him the most coins. Help him figure that out.
7+
8+
## Input
9+
10+
You will be given **_T_ Test Cases** and each test case will contain:
11+
- **First line** will have the size of grid - **M N**
12+
- Followed by a matrix of **M rows** and **N columns** of integers.
13+
14+
**Constraints**
15+
16+
- 0 < T <= 10
17+
- 0 < M,N <= 10^3
18+
- 0 <= Element <= 10^3
19+
20+
## Output
21+
22+
For each test case you will have to output one integer -> **Maximum No. of Coins**
23+
24+
## Example
25+
26+
- Input
27+
```sh
28+
4
29+
2 3
30+
1 2 0
31+
3 1 1
32+
4 3
33+
4 2 1
34+
3 5 2
35+
3 2 4
36+
4 5 1
37+
3 3
38+
6 2 3
39+
3 7 5
40+
3 3 1
41+
4 6
42+
2 9 4 3 2 5
43+
1 3 5 2 4 1
44+
6 2 3 3 5 2
45+
7 1 8 1 3 6
46+
```
47+
48+
- Output
49+
```sh
50+
6
51+
20
52+
22
53+
41
54+
```

0 commit comments

Comments
 (0)