-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdemo.cpp
More file actions
73 lines (63 loc) · 1.83 KB
/
Copy pathdemo.cpp
File metadata and controls
73 lines (63 loc) · 1.83 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
// Implemented by Kritagya Kumra
// An efficient method to find maximum value of mat[d]
// - ma[a][b] such that c > a and d > b
#include <iostream>
using namespace std;
#define N 5
// The function returns maximum value A(c,d) - A(a,b)
// over all choices of indexes such that both c > a
// and d > b.
int findMaxValue(int mat[][N])
{
// stores maximum value
int maxValue = -18999;
// maxArr[i][j] stores max of elements in matrix
// from (i, j) to (N-1, N-1)
int maxArr[N][N];
// last element of maxArr will be same's as of
// the input matrix
maxArr[N - 1][N - 1] = mat[N - 1][N - 1];
// preprocess last row
int maxv = mat[N - 1][N - 1]; // Initialize max
for (int j = N - 2; j >= 0; j--)
{
if (mat[N - 1][j] > maxv)
maxv = mat[N - 1][j];
maxArr[N - 1][j] = maxv;
}
// preprocess last column
maxv = mat[N - 1][N - 1]; // Initialize max
for (int i = N - 2; i >= 0; i--)
{
if (mat[i][N - 1] > maxv)
maxv = mat[i][N - 1];
maxArr[i][N - 1] = maxv;
}
// preprocess rest of the matrix from bottom
for (int i = N - 2; i >= 0; i--)
{
for (int j = N - 2; j >= 0; j--)
{
// Update maxValue
if (maxArr[i + 1][j + 1] - mat[i][j] >
maxValue)
maxValue = maxArr[i + 1][j + 1] - mat[i][j];
// set maxArr (i, j)
maxArr[i][j] = max(mat[i][j], max(maxArr[i][j + 1], maxArr[i + 1][j]));
}
}
return maxValue;
}
// Driver program to test above function
int main()
{
int mat[N][N] = {
{1, 2, -1, -4, -20},
{-8, -3, 4, 2, 1},
{3, 8, 6, 1, 3},
{-4, -1, 1, 7, -6},
{0, -4, 10, -5, 1}};
cout << "Maximum Value is " << findMaxValue(mat);
return 0;
}
// Implemented by Kritagya Kumra