-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathLargestZigzagSum.java
39 lines (38 loc) · 1.25 KB
/
LargestZigzagSum.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
/*https://practice.geeksforgeeks.org/problems/largest-zigzag-sequence5416/1*/
class Solution{
static int zigzagSequence(int n, int M[][]){
// code here
int[][] result = new int[n][n];
for (int i = 0; i < n; ++i)
for (int j = 0; j < n; ++j)
result[i][j] = M[i][j];
for (int i = 0; i < n; ++i)
result[n-1][i] = M[n-1][i];
for (int i = n-2; i >= 1; --i)
{
for (int j = 0; j < n; ++j)
{
int maxColVal = Integer.MIN_VALUE;
for (int k = 0; k < n; ++k)
{
if (j != k)
maxColVal = Math.max(maxColVal,result[i+1][k]+M[i][j]);
}
result[i][j] = Math.max(result[i][j],maxColVal);
}
}
int max = Integer.MIN_VALUE;
for (int j = 0; j < n; ++j)
{
int maxColVal = Integer.MIN_VALUE;
for (int k = 0; k < n; ++k)
{
if (j != k)
maxColVal = Math.max(maxColVal,result[1][k]+M[0][j]);
}
result[0][j] = Math.max(result[0][j],maxColVal);
max = Math.max(result[0][j],max);
}
return max;
}
}