Given a matrix, find the maximum sum we can have by selecting just one element from every row. Condition is element selected from nth row must be strictly greater than element from (n-1)th row, else no element must be taken from row. Print the sum if possible else print -1.
Input : 1 2 3 1 2 3 7 8 9 Output : 14 (2 + 3 + 9) (values we are adding are strictly increasing) Input : 4 2 3 3 2 1 1 2 2 Output : -1 (No subsequent increasing elements can be picked from consecutive rows)
Approach :- One can simply run the loop from last row, get the greatest element from there say it prev_max, and keep record for the minimum difference among the elements of the row just above it, if any element found with positive difference, then add it to prev_max else print -1. Continue the same process for every row.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Find maximum element of each row in a matrix
- Find row number of a binary matrix having maximum number of 1s
- Maximum Sum possible by selecting X elements from a Matrix based on given conditions
- Search in a row wise and column wise sorted matrix
- Count zeros in a row wise and column wise sorted matrix
- Search in a sorted 2D matrix (Stored in row major order)
- Leftmost Column with atleast one 1 in a row-wise sorted binary matrix
- Leftmost Column with atleast one 1 in a row-wise sorted binary matrix | Set 2
- Find the row with maximum number of 1s
- Check if each element of an Array is the Sum of any two elements of another Array
- Maximum sum subarray having sum less than or equal to given sum using Set
- Maximum size square Sub-Matrix with sum less than or equals to K
- Maximum sum path in a matrix from top-left to bottom-right
- Longest Subarrays having each Array element as the maximum
- For each element in 1st array count elements less than or equal to it in 2nd array
- Split array into subarrays at minimum cost by minimizing count of repeating elements in each subarray
- Count of Array elements greater than all elements on its left and at least K elements on its right
- Count of Array elements greater than all elements on its left and next K elements on its right
- Maximum sum of increasing order elements from n arrays
- Sum of minimum element at each depth of a given non cyclic graph
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.