Maximum sum of increasing order elements from n arrays | C # program to find maximum sum by selecting a element from n arrays ; To calculate maximum sum by selecting element from each array ; Sort each array ; Store maximum element of last array ; Selecting maximum element from previoulsy selected element ; j = - 1 means no element is found in a [ i ] so return 0 ; Driver Code
using System ; class GFG { static int M = 4 ; static void sort ( ref int [ , ] a , int row , int n ) { for ( int i = 0 ; i < M - 1 ; i ++ ) { if ( a [ row , i ] > a [ row , i + 1 ] ) { int temp = a [ row , i ] ; a [ row , i ] = a [ row , i + 1 ] ; a [ row , i + 1 ] = temp ; } } } static int maximumSum ( int [ , ] a , int n ) { int i = 0 , j = 0 ; for ( i = 0 ; i < n ; i ++ ) sort ( ref a , i , n ) ; int sum = a [ n - 1 , M - 1 ] ; int prev = a [ n - 1 , M - 1 ] ; for ( i = n - 2 ; i >= 0 ; i -- ) { for ( j = M - 1 ; j >= 0 ; j -- ) { if ( a [ i , j ] < prev ) { prev = a [ i , j ] ; sum += prev ; break ; } } if ( j == - 1 ) return 0 ; } return sum ; } static void Main ( ) { int [ , ] arr = new int [ , ] { { 1 , 7 , 3 , 4 } , { 4 , 2 , 5 , 1 } , { 9 , 5 , 1 , 8 } } ; int n = arr . GetLength ( 0 ) ; Console . Write ( maximumSum ( arr , n ) ) ; } }