Given a matrix of size n x n, find sum of the Zigzag sequence with the largest sum. A zigzag sequence starts from the top and ends at the bottom. Two consecutive elements of sequence cannot belong to same column.
Input : mat = 3 1 2 4 8 5 6 9 7 Output : 18 Zigzag sequence is: 3->8->7 Another such sequence is 2->4->7 Input : mat = 4 2 1 3 9 6 11 3 15 Output : 28
This problem has Optimal Substructure.
Maximum Zigzag sum starting from arr[i][j] to a bottom cell can be written as : zzs(i, j) = arr[i][j] + max(zzs(i+1, k)), where k = 0, 1, 2 and k != j zzs(i, j) = arr[i][j], if i = n-1 We have to find the largest among all as Result = zzs(0, j) where 0 <= j < n
Largest zigzag sum: 28
Considering the above implementation, for a matrix mat of size 3 x 3, to find zigzag sum(zzs) for an element mat(i,j), the following recursion tree is formed.
Recursion tree for cell (0, 0) zzs(0,0) / \ zzs(1,1) zzs(1,2) / \ / \ zzs(2,0) zzs(2,2) zzs(2,0) zzs(2,1) Recursion tree for cell (0, 1) zzs(0,1) / \ zzs(1,0) zzs(1,2) / \ / \ zzs(2,1) zzs(2,2) zzs(2,0) zzs(2,1) Recursion tree for cell (0, 2) zzs(0,2) / \ zzs(1,0) zzs(1,1) / \ / \ zzs(2,1) zzs(2,2) zzs(2,0) zzs(2,2)
We can see that there are many subproblems which are solved again and again. So this problem has Overlapping Substructure property and recomputation of same subproblems can be avoided by either using Memoization or Tabulation. Following is a tabluated implementation for the LIS problem.
References: Asked in Directi
This article is contributed by Ayush Jauhari. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Perfect Sum Problem (Print all subsets with given sum)
- Number of subsequences of the form a^i b^j c^k
- Gold Mine Problem
- Find Maximum dot product of two arrays with insertion of 0's
- Probability of Knight to remain in the chessboard
- Find all distinct subset (or subsequence) sums of an array
- The Two Water Jug Puzzle
- Maximum size rectangle binary sub-matrix with all 1s
- Weighted Job Scheduling in O(n Log n) time
- Count number of subsets having a particular XOR value
- Longest Zig-Zag Subsequence
- Palindrome Partitioning | DP-17
- Optimal Substructure Property in Dynamic Programming | DP-2
- Overlapping Subproblems Property in Dynamic Programming | DP-1
- Search in a row wise and column wise sorted matrix
Improved By : vt_m