text
stringlengths
17
3.65k
code
stringlengths
60
5.26k
Program for Best Fit algorithm in Memory Management | C # implementation of Best - Fit algorithm ; Method to allocate memory to blocks as per Best fit algorithm ; Stores block id of the block allocated to a process ; Initially no block is assigned to any process ; pick each process and find suitable blocks according to its size ad assign to it ; Find the best fit block for current process ; If we could find a block for current process ; allocate block j to p [ i ] process ; Reduce available memory in this block . ; Driver Method
using System ; public class GFG { static void bestFit ( int [ ] blockSize , int m , int [ ] processSize , int n ) { int [ ] allocation = new int [ n ] ; for ( int i = 0 ; i < allocation . Length ; i ++ ) allocation [ i ] = - 1 ; for ( int i = 0 ; i < n ; i ++ ) { int bestIdx = - 1 ; for ( int j = 0 ; j < m ; j ++ ) { if ( blockSize [ j ] >= processSize [ i ] ) { if ( bestIdx == - 1 ) bestIdx = j ; else if ( blockSize [ bestIdx ] > blockSize [ j ] ) bestIdx = j ; } } if ( bestIdx != - 1 ) { allocation [ i ] = bestIdx ; blockSize [ bestIdx ] -= processSize [ i ] ; } } Console . WriteLine ( " STRNEWLINE Process ▁ No . TABSYMBOL Process " + " ▁ Size TABSYMBOL Block ▁ no . " ) ; for ( int i = 0 ; i < n ; i ++ ) { Console . Write ( " ▁ " + ( i + 1 ) + " TABSYMBOL TABSYMBOL " + processSize [ i ] + " TABSYMBOL TABSYMBOL " ) ; if ( allocation [ i ] != - 1 ) Console . Write ( allocation [ i ] + 1 ) ; else Console . Write ( " Not ▁ Allocated " ) ; Console . WriteLine ( ) ; } } public static void Main ( ) { int [ ] blockSize = { 100 , 500 , 200 , 300 , 600 } ; int [ ] processSize = { 212 , 417 , 112 , 426 } ; int m = blockSize . Length ; int n = processSize . Length ; bestFit ( blockSize , m , processSize , n ) ; } }
Bin Packing Problem ( Minimize number of used Bins ) | C # program to find number of bins required using Best fit algorithm . ; Returns number of bins required using best fit online algorithm ; Initialize result ( Count of bins ) ; Create an array to store remaining space in bins there can be at most n bins ; Place items one by one ; Find the best bin that can accommodate weight [ i ] ; Initialize minimum space left and index of best bin ; If no bin could accommodate weight [ i ] , create a new bin ; Assign the item to best bin ; Driver code
using System ; class GFG { static int bestFit ( int [ ] weight , int n , int c ) { int res = 0 ; int [ ] bin_rem = new int [ n ] ; for ( int i = 0 ; i < n ; i ++ ) { int j ; int min = c + 1 , bi = 0 ; for ( j = 0 ; j < res ; j ++ ) { if ( bin_rem [ j ] >= weight [ i ] && bin_rem [ j ] - weight [ i ] < min ) { bi = j ; min = bin_rem [ j ] - weight [ i ] ; } } if ( min == c + 1 ) { bin_rem [ res ] = c - weight [ i ] ; res ++ ; } else bin_rem [ bi ] -= weight [ i ] ; } return res ; } public static void Main ( String [ ] args ) { int [ ] weight = { 2 , 5 , 4 , 7 , 1 , 3 , 8 } ; int c = 10 ; int n = weight . Length ; Console . Write ( " Number ▁ of ▁ bins ▁ required ▁ in ▁ Best ▁ Fit ▁ : ▁ " + bestFit ( weight , n , c ) ) ; } }
Bin Packing Problem ( Minimize number of used Bins ) | C # program to find number of bins required using Worst fit algorithm . ; Returns number of bins required using worst fit online algorithm ; Initialize result ( Count of bins ) ; Create an array to store remaining space in bins there can be at most n bins ; Place items one by one ; Find the best bin that ca \ n accommodate weight [ i ] ; Initialize maximum space left and index of worst bin ; If no bin could accommodate weight [ i ] , create a new bin ; else Assign the item to best bin ; Driver program
using System ; class GFG { static int worstFit ( int [ ] weight , int n , int c ) { int res = 0 ; int [ ] bin_rem = new int [ n ] ; for ( int i = 0 ; i < n ; i ++ ) { int j ; int mx = - 1 , wi = 0 ; for ( j = 0 ; j < res ; j ++ ) { if ( bin_rem [ j ] >= weight [ i ] && bin_rem [ j ] - weight [ i ] > mx ) { wi = j ; mx = bin_rem [ j ] - weight [ i ] ; } } if ( mx == - 1 ) { bin_rem [ res ] = c - weight [ i ] ; res ++ ; } bin_rem [ wi ] -= weight [ i ] ; } return res ; } public static void Main ( String [ ] args ) { int [ ] weight = { 2 , 5 , 4 , 7 , 1 , 3 , 8 } ; int c = 10 ; int n = weight . Length ; Console . Write ( " Number ▁ of ▁ bins ▁ required ▁ in ▁ Worst ▁ Fit ▁ : ▁ " + worstFit ( weight , n , c ) ) ; } }
Find minimum time to finish all jobs with given constraints | C # program to find minimum time to finish all jobs with given number of assignees ; Utility function to get maximum element in job [ 0. . n - 1 ] ; Returns true if it is possible to finish jobs [ ] within given time ' time ' ; cnt is count of current assignees required for jobs ; time assigned to current assignee ; If time assigned to current assignee exceeds max , increment count of assignees . ; Else add time of job to current time and move to next job . ; Returns true if count is smaller than k ; Returns minimum time required to finish given array of jobs k -- > number of assignees T -- > Time required by every assignee to finish 1 unit m -- > Number of jobs ; Set start and end for binary search end provides an upper limit on time ; Initialize answer ; Find the job that takes maximum time ; Do binary search for minimum feasible time ; If it is possible to finish jobs in mid time ; Update answer ; Driver program
using System ; class GFG { static int getMax ( int [ ] arr , int n ) { int result = arr [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) if ( arr [ i ] > result ) result = arr [ i ] ; return result ; } static bool isPossible ( int time , int K , int [ ] job , int n ) { int cnt = 1 ; int curr_time = 0 ; for ( int i = 0 ; i < n ; ) { if ( curr_time + job [ i ] > time ) { curr_time = 0 ; cnt ++ ; } else { curr_time += job [ i ] ; i ++ ; } } return ( cnt <= K ) ; } static int findMinTime ( int K , int T , int [ ] job , int n ) { int end = 0 , start = 0 ; for ( int i = 0 ; i < n ; ++ i ) end += job [ i ] ; int ans = end ; int job_max = getMax ( job , n ) ; while ( start <= end ) { int mid = ( start + end ) / 2 ; if ( mid >= job_max && isPossible ( mid , K , job , n ) ) { ans = Math . Min ( ans , mid ) ; end = mid - 1 ; } else start = mid + 1 ; } return ( ans * T ) ; } public static void Main ( ) { int [ ] job = { 10 , 7 , 8 , 12 , 6 , 8 } ; int n = job . Length ; int k = 4 , T = 5 ; Console . WriteLine ( findMinTime ( k , T , job , n ) ) ; } }
Longest subarray with all even or all odd elements | C # program for the above approach ; Function to calculate longest substring with odd or even elements ; Initializing dp [ ] ; Initializing dp [ 0 ] with 1 ; ans will store the final answer ; Traversing the array from index 1 to N - 1 ; Checking both current and previous element is even or odd ; Updating dp [ i ] with dp [ i - 1 ] + 1 ; Storing max element to ans ; Returning the final answer ; Driver Code ; Input ; Function call
using System ; class GFG { static int LongestOddEvenSubarray ( int [ ] A , int N ) { int [ ] dp = new int [ N ] ; dp [ 0 ] = 1 ; int ans = 1 ; for ( int i = 1 ; i < N ; i ++ ) { if ( ( A [ i ] % 2 == 0 && A [ i - 1 ] % 2 == 0 ) || ( A [ i ] % 2 != 0 && A [ i - 1 ] % 2 != 0 ) ) { dp [ i ] = dp [ i - 1 ] + 1 ; } else dp [ i ] = 1 ; } for ( int i = 0 ; i < N ; i ++ ) ans = Math . Max ( ans , dp [ i ] ) ; return ans ; } public static void Main ( ) { int [ ] A = { 2 , 5 , 7 , 2 , 4 , 6 , 8 , 3 } ; int N = A . Length ; Console . Write ( LongestOddEvenSubarray ( A , N ) ) ; } }
Count of subarrays with maximum value as K | C # program for the above approach ; Function to count the subarrays with maximum not greater than K ; If arr [ i ] > k then arr [ i ] cannot be a part of any subarray . ; Count the number of elements where arr [ i ] is not greater than k . ; Summation of all possible subarrays in the variable ans . ; Function to count the subarrays with maximum value is equal to K ; Stores count of subarrays with max <= k - 1. ; Stores count of subarrays with max >= k + 1. ; Stores count of subarrays with max = k . ; Driver Code ; Given Input ; Function Call
using System ; class GFG { static int totalSubarrays ( int [ ] arr , int n , int k ) { int ans = 0 , i = 0 ; while ( i < n ) { if ( arr [ i ] > k ) { i ++ ; continue ; } int count = 0 ; while ( i < n && arr [ i ] <= k ) { i ++ ; count ++ ; } ans += ( ( count * ( count + 1 ) ) / 2 ) ; } return ans ; } static int countSubarrays ( int [ ] arr , int n , int k ) { int count1 = totalSubarrays ( arr , n , k - 1 ) ; int count2 = totalSubarrays ( arr , n , k ) ; int ans = count2 - count1 ; return ans ; } static void Main ( ) { int n = 4 , k = 3 ; int [ ] arr = { 2 , 1 , 3 , 4 } ; Console . WriteLine ( countSubarrays ( arr , n , k ) ) ; } }
Maximum subsequence sum such that no three are consecutive in O ( 1 ) space | C # program for the above approach ; Function to calculate the maximum subsequence sum such that no three elements are consecutive ; when N is 1 , answer would be the only element present ; when N is 2 , answer would be sum of elements ; variable to store sum up to i - 3 ; variable to store sum up to i - 2 ; variable to store sum up to i - 1 ; variable to store the final sum of the subsequence ; find the maximum subsequence sum up to index i ; update first , second and third ; return ans ; ; Driver Code ; Input ; Function call
using System ; class GFG { public static int maxSumWO3Consec ( int [ ] A , int N ) { if ( N == 1 ) return A [ 0 ] ; if ( N == 2 ) return A [ 0 ] + A [ 1 ] ; int third = A [ 0 ] ; int second = third + A [ 1 ] ; int first = Math . Max ( second , A [ 1 ] + A [ 2 ] ) ; int sum = Math . Max ( Math . Max ( third , second ) , first ) ; for ( int i = 3 ; i < N ; i ++ ) { sum = Math . Max ( Math . Max ( first , second + A [ i ] ) , third + A [ i ] + A [ i - 1 ] ) ; third = second ; second = first ; first = sum ; } return sum ; } public static void Main ( ) { int [ ] A = { 3000 , 2000 , 1000 , 3 , 10 } ; int N = A . Length ; int res = maxSumWO3Consec ( A , N ) ; Console . Write ( res ) ; } }
Minimum number of given operations required to reduce a number to 2 | C # program for the above approach ; Function to find the minimum number of operations required to reduce n to 2 ; Initialize a dp array ; Handle the base case ; Iterate in the range [ 2 , n ] ; Check if i * 5 <= n ; Check if i + 3 <= n ; Return the result ; Driver code ; Given Input ; Function Call ; Print the result
using System ; using System . Collections . Generic ; class GFG { static int findMinOperations ( int n ) { int i ; int [ ] dp = new int [ n + 1 ] ; for ( i = 0 ; i < n + 1 ; i ++ ) { dp [ i ] = 999999 ; } dp [ 2 ] = 0 ; for ( i = 2 ; i < n + 1 ; i ++ ) { if ( i * 5 <= n ) { dp [ i * 5 ] = Math . Min ( dp [ i * 5 ] , dp [ i ] + 1 ) ; } if ( i + 3 <= n ) { dp [ i + 3 ] = Math . Min ( dp [ i + 3 ] , dp [ i ] + 1 ) ; } } return dp [ n ] ; } public static void Main ( ) { int n = 28 ; int m = findMinOperations ( n ) ; if ( m != 9999 ) Console . Write ( m ) ; else Console . Write ( - 1 ) ; } }
Number of M | C # program for the above approach ; Function to find the number of M - length sorted arrays possible using numbers from the range [ 1 , N ] ; Create an array of size M + 1 ; Base cases ; Fill the dp table ; dp [ j ] will be equal to maximum number of sorted array of size j when elements are taken from 1 to i ; Here dp [ m ] will be equal to the maximum number of sorted arrays when element are taken from 1 to i ; Return the result ; Driver Code ; Given Input ; Function Call
using System ; class GFG { static int countSortedArrays ( int n , int m ) { int [ ] dp = new int [ ( m + 1 ) ] ; dp [ 0 ] = 1 ; for ( int i = 1 ; i <= n ; i ++ ) { for ( int j = 1 ; j <= m ; j ++ ) { dp [ j ] = dp [ j - 1 ] + dp [ j ] ; } } return dp [ m ] ; } public static void Main ( ) { int n = 2 , m = 3 ; Console . WriteLine ( countSortedArrays ( n , m ) ) ; } }
Split array into subarrays such that sum of difference between their maximums and minimums is maximum | C # program for the above approach ; Function to find maximum sum of difference between maximums and minimums in the splitted subarrays ; Base Case ; Traverse the array ; Stores the maximum and minimum elements upto the i - th index ; Traverse the range [ 0 , i ] ; Update the minimum ; Update the maximum ; Update dp [ i ] ; Return the maximum sum of difference ; Driver Code
using System ; class GFG { static int getValue ( int [ ] arr , int N ) { int [ ] dp = new int [ N ] ; dp [ 0 ] = 0 ; for ( int i = 1 ; i < N ; i ++ ) { int min = arr [ i ] ; int max = arr [ i ] ; for ( int j = i ; j >= 0 ; j -- ) { min = Math . Min ( arr [ j ] , min ) ; max = Math . Max ( arr [ j ] , max ) ; dp [ i ] = Math . Max ( dp [ i ] , max - min + ( ( j >= 1 ) ? dp [ j - 1 ] : 0 ) ) ; } } return dp [ N - 1 ] ; } static public void Main ( ) { int [ ] arr = { 8 , 1 , 7 , 9 , 2 } ; int N = arr . Length ; Console . Write ( getValue ( arr , N ) ) ; } }
Length of longest subset consisting of A 0 s and B 1 s from an array of strings | C # program for the above approach ; Function to count 0 's in a string ; Stores count of 0 s ; Iterate over characters of string ; If current character is '0' ; Recursive function to find the length of longest subset from an array of strings with at most A 0 ' s ▁ and ▁ B ▁ 1' s ; If idx is equal to N or A + B is equal to 0 ; Stores the count of 0 's in arr[idx] ; Stores the count of 1 's in arr[idx] ; Stores the length of the subset if arr [ i ] is included ; If zero is less than or equal to A and one is less than or equal to B ; Stores the length of the subset if arr [ i ] is excluded ; Returns max of inc and exc ; Function to find the length of the longest subset from an array of strings with at most A 0 ' s ▁ and ▁ B ▁ 1' s ; Return ; Driver Code
using System ; using System . Collections . Generic ; class GFG { static int count0 ( string s ) { int count = 0 ; for ( int i = 0 ; i < s . Length ; i ++ ) { if ( s [ i ] == '0' ) { count ++ ; } } return count ; } static int solve ( List < string > vec , int A , int B , int idx ) { if ( idx == vec . Count A + B == 0 ) { return 0 ; } int zero = count0 ( vec [ idx ] ) ; int one = vec [ idx ] . Length - zero ; int inc = 0 ; if ( zero <= A && one <= B ) { inc = 1 + solve ( vec , A - zero , B - one , idx + 1 ) ; } int exc = solve ( vec , A , B , idx + 1 ) ; return Math . Max ( inc , exc ) ; } static int MaxSubsetlength ( List < string > arr , int A , int B ) { return solve ( arr , A , B , 0 ) ; } public static void Main ( ) { List < string > arr = new List < string > { "1" , "0" , "10" } ; int A = 1 , B = 1 ; Console . WriteLine ( MaxSubsetlength ( arr , A , B ) ) ; } }
Maximum score possible by removing substrings made up of single distinct character | C # program for the above approach ; Function to check if the string s consists of a single distinct character or not ; Function to calculate the maximum score possible by removing substrings ; If string is empty ; If length of string is 1 ; Store the maximum result ; Try to remove all substrings that satisfy the condition and check for resultant string after removal ; Store the substring { s [ i ] , . . , s [ j ] } ; Check if the substring contains only a single distinct character ; Return the maximum score ; Driver code
using System ; using System . Collections . Generic ; class GFG { static bool isUnique ( string s ) { HashSet < char > set = new HashSet < char > ( ) ; foreach ( char c in s ) set . Add ( c ) ; return set . Count == 1 ; } static int maxScore ( string s , int [ ] a ) { int n = s . Length ; if ( n == 0 ) return 0 ; if ( n == 1 ) return a [ 0 ] ; int mx = - 1 ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = i ; j < n ; j ++ ) { string sub = s . Substring ( i , j + 1 - i ) ; if ( isUnique ( sub ) ) mx = Math . Max ( mx , a [ sub . Length - 1 ] + maxScore ( s . Substring ( 0 , i ) + s . Substring ( j + 1 ) , a ) ) ; } } return mx ; } static void Main ( ) { string s = "011" ; int [ ] a = { 1 , 3 , 1 } ; Console . Write ( maxScore ( s , a ) ) ; } }
Maximum score possible by removing substrings made up of single distinct character | C # program for the above approach ; Initialize a dictionary to store the precomputed results ; Function to calculate the maximum score possible by removing substrings ; If s is present in dp [ ] array ; Base Cases : ; If length of string is 0 ; If length of string is 1 ; Put head pointer at start ; Initialize the max variable ; Generate the substrings using two pointers ; If s [ head ] and s [ tail ] are different ; Move head to tail and break ; Store the substring ; Update the maximum ; Move the tail ; Store the score ; Driver code
using System ; using System . Collections . Generic ; class GFG { static Dictionary < string , int > dp = new Dictionary < string , int > ( ) ; static int maxScore ( string s , int [ ] a ) { if ( dp . ContainsKey ( s ) ) return dp [ s ] ; int n = s . Length ; if ( n == 0 ) return 0 ; if ( n == 1 ) return a [ 0 ] ; int head = 0 ; int mx = - 1 ; while ( head < n ) { int tail = head ; while ( tail < n ) { if ( s [ tail ] != s [ head ] ) { head = tail ; break ; } string sub = s . Substring ( head , tail + 1 - head ) ; mx = Math . Max ( mx , a [ sub . Length - 1 ] + maxScore ( s . Substring ( 0 , head ) + s . Substring ( tail + 1 , s . Length - tail - 1 ) , a ) ) ; tail += 1 ; } if ( tail == n ) break ; } dp . Add ( s , mx ) ; return mx ; } static public void Main ( ) { string s = " abb " ; int [ ] a = { 1 , 3 , 1 } ; Console . WriteLine ( ( maxScore ( s , a ) ) ) ; } }
Count all unique outcomes possible by performing S flips on N coins | C # program for the above approach ; Dimensions of the DP table ; Stores the dp states ; Function to recursively count the number of unique outcomes possible by performing S flips on N coins ; Base Case ; If the count for the current state is not calculated , then calculate it recursively ; Otherwise return the already calculated value ; Driver Code
using System ; class GFG { static int size = 100 ; static int [ , ] ans = new int [ size , size ] ; static void initialize ( ) { for ( int i = 0 ; i < size ; i ++ ) { for ( int j = 0 ; j < size ; j ++ ) { ans [ i , j ] = 0 ; } } } static int numberOfUniqueOutcomes ( int n , int s ) { if ( s < n ) ans [ n , s ] = 0 ; else if ( n == 1 n == s ) ans [ n , s ] = 1 ; else if ( ans [ n , s ] == 0 ) { ans [ n , s ] = numberOfUniqueOutcomes ( n - 1 , s - 1 ) + numberOfUniqueOutcomes ( n - 1 , s - 2 ) ; } return ans [ n , s ] ; } public static void Main ( string [ ] args ) { initialize ( ) ; int N = 5 , S = 8 ; Console . WriteLine ( numberOfUniqueOutcomes ( N , S ) ) ; } }
Minimize removals to remove another string as a subsequence of a given string | C # program for above approach ; Function to print the minimum number of character removals required to remove X as a subsequence from the string str ; Length of the string str ; Length of the string X ; Stores the dp states ; Fill first row of dp [ ] [ ] ; If X [ j ] matches with str [ 0 ] ; If str [ i ] is equal to X [ j ] ; Update state after removing str [ i [ ; Update state after keeping str [ i ] ; If str [ i ] is not equal to X [ j ] ; Print the minimum number of characters removals ; Driver code ; Input ; Function call to get minimum number of character removals
using System ; public class GFG { static void printMinimumRemovals ( string str , string X ) { int N = str . Length ; int M = X . Length ; int [ , ] dp = new int [ N , M ] ; for ( int j = 0 ; j < M ; j ++ ) { if ( str [ 0 ] == X [ j ] ) { dp [ 0 , j ] = 1 ; } } for ( int i = 1 ; i < N ; i ++ ) { for ( int j = 0 ; j < M ; j ++ ) { if ( str [ i ] == X [ j ] ) { dp [ i , j ] = dp [ i - 1 , j ] + 1 ; if ( j != 0 ) dp [ i , j ] = Math . Min ( dp [ i , j ] , dp [ i - 1 , j - 1 ] ) ; } else { dp [ i , j ] = dp [ i - 1 , j ] ; } } } Console . WriteLine ( dp [ N - 1 , M - 1 ] ) ; } public static void Main ( String [ ] args ) { string str = " btagd " ; string X = " bad " ; printMinimumRemovals ( str , X ) ; } }
Maximum sum not exceeding K possible for any rectangle of a Matrix | C # program for the above approach ; Function to find the maximum possible sum of arectangle which is less than K ; Stores the values ( cum_sum - K ) ; Insert 0 into the set sumSet ; Traverse over the rows ; Get cumulative sum from [ 0 to i ] ; Search for upperbound of ( cSum - K ) in the hashmap ; If upper_bound of ( cSum - K ) exists , then update max sum ; Insert cummulative value in the hashmap ; Return the maximum sum which is less than K ; Function to find the maximum sum of rectangle such that its sum is no larger than K ; Stores the number of rows and columns ; Store the required result ; Set the left column ; Set the right column for the left column set by outer loop ; Calculate sum between the current left and right for every row ; Stores the sum of rectangle ; Update the overall maximum sum ; Print the result ; Driver Code ; Function Call
using System ; using System . Collections . Generic ; class GFG { static int maxSubarraySum ( int [ ] sum , int k , int row ) { int curSum = 0 , curMax = Int32 . MinValue ; HashSet < int > sumSet = new HashSet < int > ( ) ; sumSet . Add ( 0 ) ; for ( int r = 0 ; r < row ; ++ r ) { curSum += sum [ r ] ; List < int > list = new List < int > ( ) ; list . AddRange ( sumSet ) ; int it = list . LastIndexOf ( curSum - k ) ; if ( it > - 1 ) { curMax = Math . Max ( curMax , curSum - it ) ; } sumSet . Add ( curSum ) ; } return curMax ; } static void maxSumSubmatrix ( int [ , ] matrix , int k ) { int row = matrix . GetLength ( 0 ) ; int col = matrix . GetLength ( 1 ) ; int ret = Int32 . MinValue ; for ( int i = 0 ; i < col ; ++ i ) { int [ ] sum = new int [ row ] ; for ( int j = i ; j < col ; ++ j ) { for ( int r = 0 ; r < row ; ++ r ) { sum [ r ] += matrix [ r , j ] ; } int curMax = maxSubarraySum ( sum , k , row ) ; ret = Math . Max ( ret , curMax ) ; } } Console . Write ( ret ) ; } static public void Main ( ) { int [ , ] matrix = { { 1 , 0 , 1 } , { 0 , - 2 , 3 } } ; int K = 2 ; maxSumSubmatrix ( matrix , K ) ; } }
Count N | C # program for the above approach ; Function to count binary strings of length N having substring "11" ; Initialize dp [ ] of size N + 1 ; Base Cases ; Stores the first N powers of 2 ; Generate ; Iterate over the range [ 2 , N ] ; Print total count of substrings ; Driver Code
using System ; using System . Collections . Generic ; class GFG { static void binaryStrings ( int N ) { int [ ] dp = new int [ N + 1 ] ; dp [ 0 ] = 0 ; dp [ 1 ] = 0 ; int [ ] power = new int [ N + 1 ] ; power [ 0 ] = 1 ; for ( int i = 1 ; i <= N ; i ++ ) { power [ i ] = 2 * power [ i - 1 ] ; } for ( int i = 2 ; i <= N ; i ++ ) { dp [ i ] = dp [ i - 1 ] + dp [ i - 2 ] + power [ i - 2 ] ; } Console . WriteLine ( dp [ N ] ) ; } public static void Main ( ) { int N = 12 ; binaryStrings ( N ) ; } }
Maximum sum submatrix | C # program for the above approach ; Function to find maximum continuous maximum sum in the array ; Stores current and maximum sum ; Traverse the array v ; Add the value of the current element ; Update the maximum sum ; Return the maximum sum ; Function to find the maximum submatrix sum ; Store the rows and columns of the matrix ; Create an auxiliary matrix ; Traverse the matrix , prefix and initialize it will all 0 s ; Calculate prefix sum of all rows of matrix [ , ] A and store in matrix prefix [ ] ; Update the prefix [ , ] ; Store the maximum submatrix sum ; Iterate for starting column ; Iterate for last column ; To store current array elements ; Traverse every row ; Store the sum of the kth row ; Update the prefix sum ; Push it in a vector ; Update the maximum overall sum ; Print the answer ; Driver Code ; Function Call
using System ; using System . Collections . Generic ; public class GFG { static int kadane ( List < int > v ) { int currSum = 0 ; int maxSum = int . MinValue ; for ( int i = 0 ; i < ( int ) v . Count ; i ++ ) { currSum += v [ i ] ; if ( currSum > maxSum ) { maxSum = currSum ; } if ( currSum < 0 ) { currSum = 0 ; } } return maxSum ; } static void maxSubmatrixSum ( int [ , ] A ) { int r = A . GetLength ( 0 ) ; int c = A . GetLength ( 1 ) ; int [ , ] prefix = new int [ r , c ] ; for ( int i = 0 ; i < r ; i ++ ) { for ( int j = 0 ; j < c ; j ++ ) { prefix [ i , j ] = 0 ; } } for ( int i = 0 ; i < r ; i ++ ) { for ( int j = 0 ; j < c ; j ++ ) { if ( j == 0 ) prefix [ i , j ] = A [ i , j ] ; else prefix [ i , j ] = A [ i , j ] + prefix [ i , j - 1 ] ; } } int maxSum = int . MinValue ; for ( int i = 0 ; i < c ; i ++ ) { for ( int j = i ; j < c ; j ++ ) { List < int > v = new List < int > ( ) ; for ( int k = 0 ; k < r ; k ++ ) { int el = 0 ; if ( i == 0 ) el = prefix [ k , j ] ; else el = prefix [ k , j ] - prefix [ k , i - 1 ] ; v . Add ( el ) ; } maxSum = Math . Max ( maxSum , kadane ( v ) ) ; } } Console . Write ( maxSum + " STRNEWLINE " ) ; } public static void Main ( String [ ] args ) { int [ , ] matrix = { { 0 , - 2 , - 7 , 0 } , { 9 , 2 , - 6 , 2 } , { - 4 , 1 , - 4 , 1 } , { - 1 , 8 , 0 , - 2 } } ; maxSubmatrixSum ( matrix ) ; } }
Minimize cost of painting N houses such that adjacent houses have different colors | C # program for the above approach ; Function to find the minimum cost of coloring the houses such that no two adjacent houses has the same color ; Corner Case ; Auxiliary 2D dp array ; Base Case ; If current house is colored with red the take min cost of previous houses colored with ( blue and green ) ; If current house is colored with blue the take min cost of previous houses colored with ( red and green ) ; If current house is colored with green the take min cost of previous houses colored with ( red and blue ) ; Print the min cost of the last painted house ; Driver Code ; Function Call
using System ; using System . Collections . Generic ; class GFG { static int minCost ( List < List < int > > costs , int N ) { if ( N == 0 ) return 0 ; List < int > temp = new List < int > ( ) ; for ( int i = 0 ; i < 3 ; i ++ ) temp . Add ( 0 ) ; List < List < int > > dp = new List < List < int > > ( ) ; for ( int i = 0 ; i < N ; i ++ ) dp . Add ( temp ) ; dp [ 0 ] [ 0 ] = costs [ 0 ] [ 0 ] ; dp [ 0 ] [ 1 ] = costs [ 0 ] [ 1 ] ; dp [ 0 ] [ 2 ] = costs [ 0 ] [ 2 ] ; for ( int i = 1 ; i < N ; i ++ ) { dp [ i ] [ 0 ] = Math . Min ( dp [ i - 1 ] [ 1 ] , dp [ i - 1 ] [ 2 ] ) + costs [ i ] [ 0 ] ; dp [ i ] [ 1 ] = Math . Min ( dp [ i - 1 ] [ 0 ] , dp [ i - 1 ] [ 2 ] ) + costs [ i ] [ 1 ] ; dp [ i ] [ 2 ] = Math . Min ( dp [ i - 1 ] [ 0 ] , dp [ i - 1 ] [ 1 ] ) + costs [ i ] [ 2 ] ; } return ( Math . Min ( dp [ N - 1 ] [ 0 ] , Math . Min ( dp [ N - 1 ] [ 1 ] , dp [ N - 1 ] [ 2 ] ) ) ) - 11 ; } public static void Main ( ) { List < List < int > > costs = new List < List < int > > ( ) ; costs . Add ( new List < int > ( ) { 14 , 2 , 11 } ) ; costs . Add ( new List < int > ( ) { 11 , 14 , 5 } ) ; costs . Add ( new List < int > ( ) { 14 , 3 , 10 } ) ; int N = 3 ; Console . WriteLine ( ( int ) ( minCost ( costs , N ) ) ) ; } }
Minimize count of flips required to make sum of the given array equal to 0 | C # program for the above approach ; Initialize [ , ] dp ; Function to find the minimum number of operations to make sum of [ ] A 0 ; Initialize answer ; Base case ; Otherwise , return 0 ; Pre - computed subproblem ; Recurrence relation for finding the minimum of the sum of subsets ; Return the result ; Function to find the minimum number of elements required to be flipped to amke sum the array equal to 0 ; Find the sum of array ; Initialise [ , ] dp with - 1 ; No solution exists ; Otherwise ; If sum is odd , no subset is possible ; Driver Code ; Function Call
using System ; using System . Collections . Generic ; public class GFG { static int [ , ] dp = new int [ 2001 , 2001 ] ; static int solve ( int [ ] A , int i , int sum , int N ) { int res = 2001 ; if ( sum < 0 || ( i == N && sum != 0 ) ) { return 2001 ; } if ( sum == 0 i >= N ) { return dp [ i , sum ] = 0 ; } if ( dp [ i , sum ] != - 1 ) { return dp [ i , sum ] ; } res = Math . Min ( solve ( A , i + 1 , sum - A [ i ] , N ) + 1 , solve ( A , i + 1 , sum , N ) ) ; return dp [ i , sum ] = res ; } static void minOp ( int [ ] A , int N ) { int sum = 0 ; foreach ( int it in A ) { sum += it ; } if ( sum % 2 == 0 ) { for ( int i = 0 ; i < 2001 ; i ++ ) { for ( int j = 0 ; j < 2001 ; j ++ ) { dp [ i , j ] = - 1 ; } } int ans = solve ( A , 0 , sum / 2 , N ) ; if ( ans < 0 ans > N ) { Console . Write ( " - 1" + " STRNEWLINE " ) ; } else { Console . Write ( ans + " STRNEWLINE " ) ; } } else { Console . Write ( " - 1" + " STRNEWLINE " ) ; } } public static void Main ( String [ ] args ) { int [ ] A = { 2 , 3 , 1 , 4 } ; int N = A . Length ; minOp ( A , N ) ; } }
Count subsequences having average of its elements equal to K | C # program for the above approach ; Stores the dp states ; Function to find the count of subsequences having average K ; Base condition ; Three loops for three states ; Recurrence relation ; Stores the sum of dp [ n , j , K * j ] all possible values of j with average K and sum K * j ; Iterate over the range [ 1 , N ] ; Return the readonly count ; Driver Code
using System ; public class GFG { static int [ , , ] dp = new int [ 101 , 101 , 1001 ] ; static int countAverage ( int n , int K , int [ ] arr ) { dp [ 0 , 0 , 0 ] = 1 ; for ( int i = 0 ; i < n ; i ++ ) { for ( int k = 0 ; k < n ; k ++ ) { for ( int s = 0 ; s <= 100 ; s ++ ) { dp [ i + 1 , k + 1 , s + arr [ i ] ] += dp [ i , k , s ] ; dp [ i + 1 , k , s ] += dp [ i , k , s ] ; } } } int cnt = 0 ; for ( int j = 1 ; j <= n ; j ++ ) { cnt += dp [ n , j , K * j ] ; } return cnt ; } public static void Main ( String [ ] args ) { int [ ] arr = { 9 , 7 , 8 , 9 } ; int K = 8 ; int N = arr . Length ; Console . Write ( countAverage ( N , K , arr ) ) ; } }
Count ways to remove pairs from a matrix such that remaining elements can be grouped in vertical or horizontal pairs | C # program for the above approach ; Function to count ways to remove pairs such that the remaining elements can be arranged in pairs vertically or horizontally ; Store the size of matrix ; If N is odd , then no such pair exists ; Store the number of required pairs ; Initialize an auxiliary matrix and fill it with 0 s ; Traverse the matrix v [ ] [ ] ; Check if i + j is odd or even ; Increment the value dp [ v [ i ] [ j ] - 1 ] [ 0 ] by 1 ; Increment the value dp [ v [ i ] [ j ] - 1 ] [ 1 ] by 1 ; Iterate in range [ 0 , k - 1 ] using i ; Iterate in range [ i + 1 , k - 1 ] using j ; Update the ans ; Print the answer ; Driver code
using System ; using System . Collections . Generic ; class GFG { static void numberofpairs ( List < List < int > > v , int k ) { int n = v . Count ; if ( n % 2 == 1 ) { Console . Write ( 0 ) ; return ; } int ans = 0 ; int [ , ] dp = new int [ k , 2 ] ; for ( int i = 0 ; i < k ; i ++ ) { for ( int j = 0 ; j < 2 ; j ++ ) { dp [ i , j ] = 0 ; } } for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < n ; j ++ ) { if ( ( i + j ) % 2 == 0 ) dp [ v [ i ] [ j ] - 1 , 0 ] ++ ; else dp [ v [ i ] [ j ] - 1 , 1 ] ++ ; } } for ( int i = 0 ; i < k ; i ++ ) { for ( int j = i + 1 ; j < k ; j ++ ) { ans += dp [ i , 0 ] * dp [ j , 1 ] ; ans += dp [ i , 1 ] * dp [ j , 0 ] ; } } Console . Write ( ans ) ; } static void Main ( ) { List < List < int > > mat = new List < List < int > > ( ) ; mat . Add ( new List < int > ( new int [ ] { 1 , 2 } ) ) ; mat . Add ( new List < int > ( new int [ ] { 3 , 4 } ) ) ; int K = 4 ; numberofpairs ( mat , K ) ; } }
Maximize sum by selecting X different | C # program for the above approach ; Store overlapping subproblems of the recurrence relation ; Function to find maximum sum of at most N with different index array elements such that at most X are from A [ ] , Y are from B [ ] and Z are from C [ ] ; Base Cases ; If the subproblem already computed ; Selecting i - th element from A [ ] ; Selecting i - th element from B [ ] ; Selecting i - th element from C [ ] ; i - th elements not selected from any of the arrays ; Select the maximum sum from all the possible calls ; Driver Code ; Given X , Y and Z ; Given A [ ] ; Given B [ ] ; Given C [ ] ; Given Size ; Function Call
using System ; class GFG { static int [ , , , ] dp = new int [ 50 , 50 , 50 , 50 ] ; static int FindMaxS ( int X , int Y , int Z , int n , int [ ] A , int [ ] B , int [ ] C ) { if ( X < 0 Y < 0 Z < 0 ) return Int32 . MinValue ; if ( n < 0 ) return 0 ; if ( dp [ n , X , Y , Z ] != - 1 ) { return dp [ n , X , Y , Z ] ; } int ch = A [ n ] + FindMaxS ( X - 1 , Y , Z , n - 1 , A , B , C ) ; int ca = B [ n ] + FindMaxS ( X , Y - 1 , Z , n - 1 , A , B , C ) ; int co = C [ n ] + FindMaxS ( X , Y , Z - 1 , n - 1 , A , B , C ) ; int no = FindMaxS ( X , Y , Z , n - 1 , A , B , C ) ; int maximum = Math . Max ( ch , Math . Max ( ca , Math . Max ( co , no ) ) ) ; return dp [ n , X , Y , Z ] = maximum ; } public static void Main ( string [ ] args ) { int X = 1 ; int Y = 1 ; int Z = 1 ; int [ ] A = { 10 , 0 , 5 } ; int [ ] B = { 5 , 10 , 0 } ; int [ ] C = { 0 , 5 , 10 } ; int n = B . Length ; for ( int i = 0 ; i < 50 ; i ++ ) for ( int j = 0 ; j < 50 ; j ++ ) for ( int k = 0 ; k < 50 ; k ++ ) for ( int l = 0 ; l < 50 ; l ++ ) dp [ i , j , k , l ] = - 1 ; Console . Write ( FindMaxS ( X , Y , Z , n - 1 , A , B , C ) ) ; } }
Minimize swaps of adjacent characters to sort every possible rearrangement of given Binary String | C # program for the above approach ; Precalculate the values of power of 2 ; Function to calculate 2 ^ N % mod ; Function to find sum of inversions ; Initialise a list of 0 s and ? s ; Traverse the string in the reversed manner ; If the current character is 1 ; Effectively calculate a * b ^ ( b - 1 ) ; If the current character is 0 ; Increment count of zeroes ; Double count the zeroes ; Find b * 2 ^ ( b - 1 ) ; Increment count of questions ; Return the final count ; Driver code ; Given string S ; Function Call
using System ; using System . Collections . Generic ; class GFG { static int MOD = 1000000007 ; static List < int > MEM = new List < int > ( new int [ ] { 1 , 2 , 4 , 8 , 16 , 32 , 64 , 128 , 256 , 512 , 1024 , 2048 , 4096 } ) ; static int mod_pow2 ( int n ) { while ( n >= MEM . Count ) MEM . Add ( ( MEM [ MEM . Count - 1 ] * 2 ) % MOD ) ; return MEM [ n ] ; } static int inversions ( char [ ] bstr ) { int total = 0 , zeros = 0 , questions = 0 ; Array . Reverse ( bstr ) ; foreach ( char x in bstr ) { int q ; if ( x == '1' ) { int z = zeros * mod_pow2 ( questions ) ; if ( questions == 0 ) q = 0 ; else q = questions * mod_pow2 ( questions - 1 ) ; total = ( total + z + q ) % MOD ; } else if ( x == '0' ) { zeros += 1 ; } else { total *= 2 ; int z = zeros * mod_pow2 ( questions ) ; if ( questions == 0 ) q = 0 ; else q = questions * mod_pow2 ( questions - 1 ) ; total = ( total + z + q ) % MOD ; questions += 1 ; } } return total ; } static void Main ( ) { char [ ] S = " ? 0 ? " . ToCharArray ( ) ; Console . WriteLine ( inversions ( S ) ) ; } }
Minimum removals required to convert given array to a Mountain Array | C # program of the above approach ; Utility function to count array elements required to be removed to make array a mountain array ; Stores length of increasing subsequence from [ 0 , i - 1 ] ; Stores length of increasing subsequence from [ i + 1 , n - 1 ] ; Iterate for each position up to N - 1 to find the length of subsequence ; If j is less than i , then i - th position has leftIncreasing [ j ] + 1 lesser elements including itself ; Check if it is the maximum obtained so far ; Search for increasing subsequence from right ; Find the position following the peak condition and have maximum leftIncreasing [ i ] + rightIncreasing [ i ] ; Function to count elements to be removed to make array a mountain array ; Print the answer ; Driver Code ; Given array ; Function Call
using System ; class GFG { public static int minRemovalsUtil ( int [ ] arr ) { int result = 0 ; if ( arr . Length < 3 ) { return - 1 ; } int [ ] leftIncreasing = new int [ arr . Length ] ; int [ ] rightIncreasing = new int [ arr . Length ] ; for ( int i = 1 ; i < arr . Length ; i ++ ) { for ( int j = 0 ; j < i ; j ++ ) { if ( arr [ j ] < arr [ i ] ) { leftIncreasing [ i ] = Math . Max ( leftIncreasing [ i ] , leftIncreasing [ j ] + 1 ) ; } } } for ( int i = arr . Length - 2 ; i >= 0 ; i -- ) { for ( int j = arr . Length - 1 ; j > i ; j -- ) { if ( arr [ j ] < arr [ i ] ) { rightIncreasing [ i ] = Math . Max ( rightIncreasing [ i ] , rightIncreasing [ j ] + 1 ) ; } } } for ( int i = 0 ; i < arr . Length ; i ++ ) { if ( leftIncreasing [ i ] != 0 && rightIncreasing [ i ] != 0 ) { result = Math . Max ( result , leftIncreasing [ i ] + rightIncreasing [ i ] ) ; } } return arr . Length - ( result + 1 ) ; } public static void minRemovals ( int [ ] arr ) { int ans = minRemovalsUtil ( arr ) ; Console . WriteLine ( ans ) ; } public static void Main ( String [ ] args ) { int [ ] arr = { 2 , 1 , 1 , 5 , 6 , 2 , 3 , 1 } ; minRemovals ( arr ) ; } }
Count of numbers from range [ L , R ] whose sum of digits is Y | Set 2 | C # program for the above approach ; Function to find the sum of digits of numbers in the range [ 0 , X ] ; Check if count of digits in a number greater than count of digits in X ; Check Iif sum of digits of a number is equal to Y ; Stores count of numbers whose sum of digits is Y ; Check if the number exceeds Y or not ; Iterate over all possible values of i - th digits ; Update res ; Return res ; Utility function to count the numbers in the range [ L , R ] whose sum of digits is Y ; Base Case ; Stores numbers in the form of its equivalent String ; Stores count of numbers in the range [ 0 , R ] ; Update str ; Stores count of numbers in the range [ 0 , L - 1 ] ; Driver Code
using System ; class GFG { static int cntNum ( string X , int i , int sum , int tight ) { if ( i >= X . Length sum < 0 ) { if ( sum == 0 ) { return 1 ; } return 0 ; } int res = 0 ; int end = tight != 0 ? X [ i ] - '0' : 9 ; for ( int j = 0 ; j <= end ; j ++ ) { res += cntNum ( X , i + 1 , sum - j , ( tight > 0 & ( j == end ) ) == true ? 1 : 0 ) ; } return res ; } static int UtilCntNumRange ( int L , int R , int Y ) { if ( R == 0 && Y == 0 ) { return 1 ; } string str = R . ToString ( ) ; int cntR = cntNum ( str , 0 , Y , 1 ) ; str = ( L - 1 ) . ToString ( ) ; int cntL = cntNum ( str , 0 , Y , 1 ) ; return ( cntR - cntL ) ; } public static void Main ( string [ ] args ) { int L = 20 , R = 10000 , Y = 14 ; Console . WriteLine ( UtilCntNumRange ( L , R , Y ) ) ; } }
Longest subsequence having maximum GCD between any pair of distinct elements | C # program for the above approach ; Recursive function to return gcd of a and b ; Function to find GCD of pair with maximum GCD ; Stores maximum element of [ ] arr ; Find the maximum element ; Maintain a count array ; Store the frequency of [ ] arr ; Stores the multiples of a number ; Iterate over the range [ MAX , 1 ] ; Iterate from current potential GCD till it is less than MAX ; A multiple found ; Increment potential GCD by itself io check i , 2 i , 3 i ... ; If 2 multiples found max GCD found ; Function to find longest subsequence such that GCD of any two distinct integers is maximum ; Base Cases ; Compare current GCD to the maximum GCD ; If true increment and move the pointer ; Return max of either subsequences ; Driver Code ; Sorted array ; Function call to calculate GCD of pair with maximum GCD ; Print the result
using System ; class GFG { static int __gcd ( int a , int b ) { return b == 0 ? a : __gcd ( b , a % b ) ; } static int findMaxGCD ( int [ ] arr , int N ) { int high = 0 ; for ( int i = 0 ; i < N ; i ++ ) { high = Math . Max ( high , arr [ i ] ) ; } int [ ] count = new int [ high + 1 ] ; for ( int i = 0 ; i < N ; i ++ ) { count [ arr [ i ] ] += 1 ; } int counter = 0 ; for ( int i = high ; i > 0 ; i -- ) { int j = i ; while ( j <= high ) { if ( count [ j ] > 0 ) counter += count [ j ] ; j += i ; if ( counter == 2 ) return i ; } counter = 0 ; } return 0 ; } static int maxlen ( int i , int j , int [ ] arr , int [ ] arr1 , int N , int maxgcd ) { int a = 1 ; if ( i >= N j >= N ) return 0 ; if ( __gcd ( arr [ i ] , arr1 [ j ] ) == maxgcd && arr [ i ] != arr1 [ j ] ) { a = Math . Max ( a , 1 + maxlen ( i , j + 1 , arr , arr1 , N , maxgcd ) ) ; return a ; } return Math . Max ( maxlen ( i + 1 , j , arr , arr1 , N , maxgcd ) , maxlen ( i , j + 1 , arr , arr1 , N , maxgcd ) ) ; } public static void Main ( String [ ] args ) { int [ ] arr = { 1 , 2 , 8 , 5 , 6 } ; int [ ] arr1 = { 1 , 2 , 8 , 5 , 6 } ; int n = arr . Length ; Array . Sort ( arr ) ; int maxgcd = findMaxGCD ( arr , n ) ; Console . Write ( maxlen ( 0 , 0 , arr , arr1 , n , maxgcd ) ) ; } }
Generate a combination of minimum coins that sums to a given value | C # program for the above approach ; dp array to memoize the results ; List to store the result ; Function to find the minimum number of coins to make the sum equals to X ; Base case ; If previously computed subproblem occurred ; Initialize result ; Try every coin that has smaller value than n ; Check for int . MaxValue to avoid overflow and see if result can be minimized ; Memoizing value of current state ; Function to find the possible combination of coins to make the sum equal to X ; Base Case ; Print Solutions ; Try every coin that has value smaller than n ; Add current denominations ; Backtrack ; Function to find the minimum combinations of coins for value X ; Initialize dp with - 1 ; Min coins ; If no solution exists ; Backtrack to find the solution ; Driver code ; Set of possible denominations ; Function Call
using System ; using System . Collections . Generic ; class GFG { static readonly int MAX = 100000 ; static int [ ] dp = new int [ MAX + 1 ] ; static List < int > denomination = new List < int > ( ) ; static int countMinCoins ( int n , int [ ] C , int m ) { if ( n == 0 ) { dp [ 0 ] = 0 ; return 0 ; } if ( dp [ n ] != - 1 ) return dp [ n ] ; int ret = int . MaxValue ; for ( int i = 0 ; i < m ; i ++ ) { if ( C [ i ] <= n ) { int x = countMinCoins ( n - C [ i ] , C , m ) ; if ( x != int . MaxValue ) ret = Math . Min ( ret , 1 + x ) ; } } dp [ n ] = ret ; return ret ; } static void findSolution ( int n , int [ ] C , int m ) { if ( n == 0 ) { foreach ( int it in denomination ) { Console . Write ( it + " ▁ " ) ; } return ; } for ( int i = 0 ; i < m ; i ++ ) { if ( n - C [ i ] >= 0 && dp [ n - C [ i ] ] + 1 == dp [ n ] ) { denomination . Add ( C [ i ] ) ; findSolution ( n - C [ i ] , C , m ) ; break ; } } } static void countMinCoinsUtil ( int X , int [ ] C , int N ) { for ( int i = 0 ; i < dp . Length ; i ++ ) dp [ i ] = - 1 ; int isPossible = countMinCoins ( X , C , N ) ; if ( isPossible == int . MaxValue ) { Console . Write ( " - 1" ) ; } else { findSolution ( X , C , N ) ; } } public static void Main ( String [ ] args ) { int X = 21 ; int [ ] arr = { 2 , 3 , 4 , 5 } ; int N = arr . Length ; countMinCoinsUtil ( X , arr , N ) ; } }
Count all possible paths from top left to bottom right of a Matrix without crossing the diagonal | C # Program to implement the above approach ; Function to calculate Binomial Coefficient C ( n , r ) ; C ( n , r ) = C ( n , n - r ) ; [ n * ( n - 1 ) * -- - * ( n - r + 1 ) ] / [ r * ( r - 1 ) * -- -- * 1 ] ; Function to calculate the total possible paths ; Update n to n - 1 as ( N - 1 ) catalan number is the result ; Stores 2 nCn ; Stores Nth Catalan number ; Stores the required answer ; Driver Code
using System ; class GFG { static int binCoff ( int n , int r ) { int val = 1 ; int i ; if ( r > ( n - r ) ) { r = ( n - r ) ; } for ( i = 0 ; i < r ; i ++ ) { val *= ( n - i ) ; val /= ( i + 1 ) ; } return val ; } static int findWays ( int n ) { n -- ; int a , b , ans ; a = binCoff ( 2 * n , n ) ; b = a / ( n + 1 ) ; ans = 2 * b ; return ans ; } public static void Main ( String [ ] args ) { int n = 4 ; Console . Write ( findWays ( n ) ) ; } }
Minimum operations to transform given string to another by moving characters to front or end | C # program for the above approach ; Function that finds the minimum number of steps to find the minimum characters must be moved to convert String s to t ; r = maximum value over all dp [ i , j ] computed so far ; dp [ i , j ] stores the longest contiguous suffix of T [ 0. . j ] that is subsequence of S [ 0. . i ] ; Update the maximum length ; Return the resulting length ; Driver Code ; Given String s , t ; Function Call
using System ; class GFG { static int [ , ] dp = new int [ 1010 , 1010 ] ; static int solve ( String s , String t ) { int n = s . Length ; int r = 0 ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < n ; j ++ ) { dp [ i , j ] = 0 ; if ( i > 0 ) { dp [ i , j ] = Math . Max ( dp [ i - 1 , j ] , dp [ i , j ] ) ; } if ( s [ i ] == t [ j ] ) { int ans = 1 ; if ( i > 0 && j > 0 ) { ans = 1 + dp [ i - 1 , j - 1 ] ; } dp [ i , j ] = Math . Max ( dp [ i , j ] , ans ) ; r = Math . Max ( r , dp [ i , j ] ) ; } } } return ( n - r ) ; } public static void Main ( String [ ] args ) { String s = " abcde " ; String t = " edacb " ; Console . Write ( solve ( s , t ) ) ; } }
Longest substring whose characters can be rearranged to form a Palindrome | C # program for the above approach ; Function to get the length of longest substring whose characters can be arranged to form a palindromic string ; To keep track of the last index of each xor ; Initialize answer with 0 ; Now iterate through each character of the string ; Convert the character from [ a , z ] to [ 0 , 25 ] ; Turn the temp - th bit on if character occurs odd number of times and turn off the temp - th bit off if the character occurs ever number of times ; If a mask is present in the index Therefore a palindrome is found from index [ mask ] to i ; If x is not found then add its position in the index dict . ; Check for the palindrome of odd length ; We cancel the occurrence of a character if it occurs odd number times ; Driver code ; Given String ; Length of given string ; Function call
using System . Collections . Generic ; using System ; class GFG { static int longestSubstring ( string s , int n ) { Dictionary < int , int > index = new Dictionary < int , int > ( ) ; int answer = 0 ; int mask = 0 ; index [ mask ] = - 1 ; for ( int i = 0 ; i < n ; i ++ ) { int temp = ( int ) s [ i ] - 97 ; mask ^= ( 1 << temp ) ; if ( index . ContainsKey ( mask ) == true ) { answer = Math . Max ( answer , i - index [ mask ] ) ; } else index [ mask ] = i ; for ( int j = 0 ; j < 26 ; j ++ ) { int mask2 = mask ^ ( 1 << j ) ; if ( index . ContainsKey ( mask2 ) == true ) { answer = Math . Max ( answer , i - index [ mask2 ] ) ; } } } return answer ; } public static void Main ( ) { string s = " adbabd " ; int n = s . Length ; Console . WriteLine ( longestSubstring ( s , n ) ) ; } }
Count of N | C # program for the above approach ; Function to find count of N - digit numbers with single digit XOR ; dp [ i ] [ j ] stores the number of i - digit numbers with XOR equal to j ; For 1 - 9 store the value ; Iterate till N ; Calculate XOR ; Store in DP table ; Initialize count ; Print the answer ; Driver Code ; Given number N ; Function call
using System ; class GFG { public static void countNums ( int N ) { int [ , ] dp = new int [ N , 16 ] ; for ( int i = 1 ; i <= 9 ; i ++ ) dp [ 0 , i ] = 1 ; for ( int i = 1 ; i < N ; i ++ ) { for ( int j = 0 ; j < 10 ; j ++ ) { for ( int k = 0 ; k < 16 ; k ++ ) { int xor = j ^ k ; dp [ i , xor ] += dp [ i - 1 , k ] ; } } } int count = 0 ; for ( int i = 0 ; i < 10 ; i ++ ) count += dp [ N - 1 , i ] ; Console . Write ( count ) ; } public static void Main ( string [ ] args ) { int N = 1 ; countNums ( N ) ; } }
Print the Maximum Subarray Sum | C # program for the above approach ; Function to print the elements of Subarray with maximum sum ; Initialize currMax and globalMax with first value of nums ; Initialize endIndex startIndex , globalStartIndex ; Iterate for all the elemensts of the array ; Update currMax and startIndex ; startIndex = i ; update the new startIndex ; Update currMax ; Update globalMax anf globalMaxStartIndex ; Printing the elements of subarray with max sum ; Driver Code ; Given array arr [ ] ; Function call
using System ; using System . Collections . Generic ; public class GFG { static void SubarrayWithMaxSum ( List < int > nums ) { int currMax = nums [ 0 ] , globalMax = nums [ 0 ] ; int endIndex = 0 ; int startIndex = 0 , globalMaxStartIndex = 0 ; for ( int i = 1 ; i < nums . Count ; ++ i ) { if ( nums [ i ] > nums [ i ] + currMax ) { currMax = nums [ i ] ; } else if ( nums [ i ] < nums [ i ] + currMax ) { currMax = nums [ i ] + currMax ; } if ( currMax > globalMax ) { globalMax = currMax ; endIndex = i ; globalMaxStartIndex = startIndex ; } } for ( int i = globalMaxStartIndex ; i <= endIndex ; ++ i ) { Console . Write ( nums [ i ] + " ▁ " ) ; } } static public void Main ( ) { List < int > arr = new List < int > ( ) ; arr . Add ( - 2 ) ; arr . Add ( - 5 ) ; arr . Add ( 6 ) ; arr . Add ( - 2 ) ; arr . Add ( - 3 ) ; arr . Add ( 1 ) ; arr . Add ( 5 ) ; arr . Add ( - 6 ) ; SubarrayWithMaxSum ( arr ) ; } }
Count of numbers upto M divisible by given Prime Numbers | C # program for the above approach ; Function to count the numbers that are divisible by the numbers in the array from range 1 to M ; Initialize the count variable ; Iterate over [ 1 , M ] ; Iterate over array elements [ ] arr ; Check if i is divisible by a [ j ] ; Increment the count ; Return the answer ; Driver code ; Given array [ ] arr ; Given number M ; Function call
using System ; class GFG { static int count ( int [ ] a , int M , int N ) { int cnt = 0 ; for ( int i = 1 ; i <= M ; i ++ ) { for ( int j = 0 ; j < N ; j ++ ) { if ( i % a [ j ] == 0 ) { cnt ++ ; break ; } } } return cnt ; } public static void Main ( String [ ] args ) { int [ ] arr = { 2 , 3 , 5 , 7 } ; int m = 100 ; int n = arr . Length ; Console . Write ( count ( arr , m , n ) ) ; } }
Count of numbers upto N digits formed using digits 0 to K | C # implementation to count the numbers upto N digits such that no two zeros are adjacent ; Function to count the numbers upto N digits such that no two zeros are adjacent ; Condition to check if only one element remains ; If last element is non zero , return K - 1 ; If last element is 0 ; Condition to check if value calculated already ; If last element is non zero , then two cases arise , current element can be either zero or non zero ; Memoize this case ; If last is 0 , then current can only be non zero ; Memoize and return ; Driver Code ; Given N and K ; Function Call
using System ; class GFG { public static int [ , ] dp = new int [ 15 , 10 ] ; public static int solve ( int n , int last , int k ) { if ( n == 1 ) { if ( last == k ) { return ( k - 1 ) ; } else { return 1 ; } } if ( dp [ n , last ] == 1 ) return dp [ n , last ] ; if ( last == k ) { return dp [ n , last ] = ( k - 1 ) * solve ( n - 1 , k , k ) + ( k - 1 ) * solve ( n - 1 , 1 , k ) ; } else { return dp [ n , last ] = solve ( n - 1 , k , k ) ; } } public static void Main ( string [ ] args ) { int n = 2 , k = 3 ; int x = solve ( n , k , k ) + solve ( n , 1 , k ) ; Console . WriteLine ( x ) ; } }
Count of occurrences of each prefix in a string using modified KMP algorithm | C # program for the above approach ; Function to print the count of all prefix in the given String ; Iterate over String s ; Print the prefix and their frequency ; Function to implement the LPS array to store the longest prefix which is also a suffix for every subString of the String S ; Array to store LPS values ; Value of lps [ 0 ] is 0 by definition ; Find the values of LPS [ i ] for the rest of the String using two pointers and DP ; Initially set the value of j as the longest prefix that is also a suffix for i as LPS [ i - 1 ] ; Check if the suffix of length j + 1 is also a prefix ; If s [ i ] = s [ j ] then , assign LPS [ i ] as j + 1 ; If we reached j = 0 , assign LPS [ i ] as 0 as there was no prefix equal to suffix ; Return the calculated LPS array ; Function to count the occurrence of all the prefix in the String S ; Call the prefix_function to get LPS ; To store the occurrence of all the prefix ; Count all the suffixes that are also prefix ; Add the occurences of i to smaller prefixes ; Adding 1 to all occ [ i ] for all the orignal prefix ; Function Call to print the occurence of all the prefix ; Driver Code ; Given String ; Function Call
using System ; class GFG { static void print ( int [ ] occ , String s ) { for ( int i = 1 ; i <= s . Length - 1 ; i ++ ) { Console . Write ( s . Substring ( 0 , i ) + " ▁ occurs ▁ " + occ [ i ] + " ▁ times . " + " STRNEWLINE " ) ; } } static int [ ] prefix_function ( String s ) { int [ ] LPS = new int [ s . Length ] ; LPS [ 0 ] = 0 ; for ( int i = 1 ; i < s . Length ; i ++ ) { int j = LPS [ i - 1 ] ; while ( j > 0 && s [ i ] != s [ j ] ) { j = LPS [ j - 1 ] ; } if ( s [ i ] == s [ j ] ) { LPS [ i ] = j + 1 ; } else { LPS [ i ] = 0 ; } } return LPS ; } static void count_occurence ( String s ) { int n = s . Length ; int [ ] LPS = prefix_function ( s ) ; int [ ] occ = new int [ n + 1 ] ; for ( int i = 0 ; i < n ; i ++ ) { occ [ LPS [ i ] ] ++ ; } for ( int i = n - 1 ; i > 0 ; i -- ) { occ [ LPS [ i - 1 ] ] += occ [ i ] ; } for ( int i = 0 ; i <= n ; i ++ ) occ [ i ] ++ ; print ( occ , s ) ; } public static void Main ( String [ ] args ) { String A = " ABACABA " ; count_occurence ( A ) ; } }
Maximum sum by picking elements from two arrays in order | Set 2 | C # program to find maximum sum possible by selecting an element from one of two arrays for every index ; Function to calculate maximum sum ; Maximum elements that can be chosen from array A ; Maximum elements that can be chosen from array B ; Stores the maximum sum possible ; Fill the [ , ] dp for base case when all elements are selected from [ ] A ; Fill the [ , ] dp for base case when all elements are selected from [ ] B ; Return the readonly answer ; Driver code
using System ; class GFG { static int maximumSum ( int [ ] A , int [ ] B , int length , int X , int Y ) { int l = length ; int l1 = Math . Min ( length , X ) ; int l2 = Math . Min ( length , Y ) ; int [ , ] dp = new int [ l1 + 1 , l2 + 1 ] ; int max_sum = int . MinValue ; for ( int i = 1 ; i <= l1 ; i ++ ) { dp [ i , 0 ] = dp [ i - 1 , 0 ] + A [ i - 1 ] ; max_sum = Math . Max ( max_sum , dp [ i , 0 ] ) ; } for ( int i = 1 ; i <= l2 ; i ++ ) { dp [ 0 , i ] = dp [ 0 , i - 1 ] + B [ i - 1 ] ; max_sum = Math . Max ( max_sum , dp [ 0 , i ] ) ; } for ( int i = 1 ; i <= l1 ; i ++ ) { for ( int j = 1 ; j <= l2 ; j ++ ) { if ( i + j <= l ) dp [ i , j ] = Math . Max ( dp [ i - 1 , j ] + A [ i + j - 1 ] , dp [ i , j - 1 ] + B [ i + j - 1 ] ) ; max_sum = Math . Max ( dp [ i , j ] , max_sum ) ; } } return max_sum ; } public static void Main ( String [ ] args ) { int [ ] A = new int [ ] { 1 , 2 , 3 , 4 , 5 } ; int [ ] B = new int [ ] { 5 , 4 , 3 , 2 , 1 } ; int X = 3 , Y = 2 ; int N = A . Length ; Console . WriteLine ( maximumSum ( A , B , N , X , Y ) ) ; } }
Min number of operations to reduce N to 0 by subtracting any digits from N | C # program for the above approach ; Function to reduce an integer N to Zero in minimum operations by removing digits from N ; Initialise [ ] dp to steps ; Iterate for all elements ; For each digit in number i ; Either select the number or do not select it ; dp [ N ] will give minimum step for N ; Driver Code ; Given Number ; Function Call
using System ; class GFG { static int reduceZero ( int N ) { int [ ] dp = new int [ N + 1 ] ; for ( int i = 0 ; i <= N ; i ++ ) dp [ i ] = ( int ) 1e9 ; dp [ 0 ] = 0 ; for ( int i = 0 ; i <= N ; i ++ ) { foreach ( char c in String . Join ( " " , i ) . ToCharArray ( ) ) { dp [ i ] = Math . Min ( dp [ i ] , dp [ i - ( c - '0' ) ] + 1 ) ; } } return dp [ N ] ; } public static void Main ( String [ ] args ) { int N = 25 ; Console . Write ( reduceZero ( N ) ) ; } }
Pentanacci Numbers | C # implementation to print Nth Pentanacci numbers . ; Function to print Nth Pentanacci number ; Initialize first five numbers to base cases ; Declare a current variable ; Loop to add previous five numbers for each number starting from 5 and then assign first , second , third , fourth to second , third , fourth and curr to fifth respectively ; Driver code
using System ; class GFG { static void printpenta ( int n ) { if ( n < 0 ) return ; int first = 0 ; int second = 0 ; int third = 0 ; int fourth = 0 ; int fifth = 1 ; int curr = 0 ; if ( n == 0 n == 1 n == 2 n == 3 ) Console . Write ( first + " STRNEWLINE " ) ; else if ( n == 5 ) Console . Write ( fifth + " STRNEWLINE " ) ; else { for ( int i = 5 ; i < n ; i ++ ) { curr = first + second + third + fourth + fifth ; first = second ; second = third ; third = fourth ; fourth = fifth ; fifth = curr ; } Console . Write ( curr + " STRNEWLINE " ) ; } } public static void Main ( String [ ] args ) { int n = 10 ; printpenta ( n ) ; } }
Count of binary strings of length N with even set bit count and at most K consecutive 1 s | C # program for the above approach ; Table to store solution of each subproblem ; Function to calculate the possible binary Strings ; If number of ones is equal to K ; pos : current position Base Case : When n length is traversed ; sum : count of 1 ' s ▁ ▁ Return ▁ the ▁ count ▁ ▁ of ▁ 1' s obtained ; If the subproblem has already been solved ; Return the answer ; Recursive call when current position is filled with 1 ; Recursive call when current position is filled with 0 ; Store the solution to this subproblem ; Driver Code ; Initialising the table with - 1
using System ; class GFG { static int [ , , ] dp = new int [ 100001 , 20 , 2 ] ; static int possibleBinaries ( int pos , int ones , int sum , int k ) { if ( ones == k ) return 0 ; if ( pos == 0 ) return ( sum == 0 ) ? 1 : 0 ; if ( dp [ pos , ones , sum ] != - 1 ) return dp [ pos , ones , sum ] ; int ret = possibleBinaries ( pos - 1 , ones + 1 , ( sum + 1 ) % 2 , k ) + possibleBinaries ( pos - 1 , 0 , sum , k ) ; dp [ pos , ones , sum ] = ret ; return dp [ pos , ones , sum ] ; } public static void Main ( String [ ] args ) { int N = 3 ; int K = 2 ; for ( int i = 0 ; i < 100001 ; i ++ ) { for ( int j = 0 ; j < 20 ; j ++ ) { for ( int l = 0 ; l < 2 ; l ++ ) dp [ i , j , l ] = - 1 ; } } Console . Write ( possibleBinaries ( N , 0 , 0 , K ) ) ; } }
Count of ways to traverse a Matrix and return to origin in K steps | C # program to count total number of ways to return to origin after completing given number of steps . ; Function Initialize [ , ] dp [ ] array with - 1 ; Function returns the total count ; Driver code
using System ; class GFG { static int [ , , ] dp = new int [ 101 , 101 , 101 ] ; static int N , M , K ; static int MOD = 1000000007 ; public static void Initialize ( ) { for ( int i = 0 ; i <= 100 ; i ++ ) for ( int j = 0 ; j <= 100 ; j ++ ) for ( int z = 0 ; z <= 100 ; z ++ ) dp [ i , j , z ] = - 1 ; } public static int CountWays ( int i , int j , int k ) { if ( i >= N i < 0 j >= M j < 0 k < 0 ) return 0 ; if ( i == 0 && j == 0 && k == 0 ) return 1 ; if ( dp [ i , j , k ] != - 1 ) return dp [ i , j , k ] ; else dp [ i , j , k ] = ( CountWays ( i + 1 , j , k - 1 ) % MOD + CountWays ( i - 1 , j , k - 1 ) % MOD + CountWays ( i , j - 1 , k - 1 ) % MOD + CountWays ( i , j + 1 , k - 1 ) % MOD + CountWays ( i , j , k - 1 ) % MOD ) % MOD ; return dp [ i , j , k ] ; } public static void Main ( String [ ] args ) { N = 3 ; M = 3 ; K = 4 ; Initialize ( ) ; Console . WriteLine ( CountWays ( 0 , 0 , K ) ) ; } }
Count of subsequences of length atmost K containing distinct prime elements | C # Program to find the count of distinct prime subsequences at most of of length K from a given array ; Initialize all indices as true ; A value in prime [ i ] will finally be false if i is not a prime , else true ; If prime [ p ] is true , then it is a prime ; Update all multiples of p as false , i . e . non - prime ; Returns number of subsequences of maximum length k and contains distinct primes ; Store the primes in the given array ; Sort the primes ; Store the frequencies of all the distinct primes ; Store the frequency of primes ; Store the sum of all frequencies ; Store the length of subsequence at every instant ; Store the frequency ; Store the previous count of updated DP ; Calculate total subsequences of current of_length ; Add the number of subsequences to the answer ; Update the value in dp [ i ] ; Store the updated dp [ i ] ; Driver Code
using System ; using System . Collections . Generic ; class GFG { static bool [ ] prime = new bool [ 100001 ] ; static void SieveOfEratosthenes ( ) { for ( int i = 0 ; i < prime . Length ; i ++ ) prime [ i ] = true ; prime [ 0 ] = prime [ 1 ] = false ; for ( int p = 2 ; p * p < 100000 ; p ++ ) { if ( prime [ p ] == true ) { for ( int i = p * p ; i <= 100000 ; i += p ) prime [ i ] = false ; } } } static int distinctPrimeSubSeq ( int [ ] a , int n , int k ) { SieveOfEratosthenes ( ) ; List < int > primes = new List < int > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( prime [ a [ i ] ] ) primes . Add ( a [ i ] ) ; } int l = primes . Count ; primes . Sort ( ) ; List < int > b = new List < int > ( ) ; List < int > dp = new List < int > ( ) ; int sum = 0 ; for ( int i = 0 ; i < l ; ) { int count = 1 , x = a [ i ] ; i ++ ; while ( i < l && a [ i ] == x ) { count ++ ; i ++ ; } b . Add ( count ) ; dp . Add ( count ) ; sum += count ; } int of_length = 2 ; int len = dp . Count ; int ans = 0 ; while ( of_length <= k ) { int freq = 0 ; int prev = 0 ; for ( int i = 0 ; i < ( len ) ; i ++ ) { freq += dp [ i ] ; int j = sum - freq ; int subseq = b [ i ] * j ; ans += subseq ; dp [ i ] = subseq ; prev += dp [ i ] ; } len -- ; sum = prev ; of_length ++ ; } ans += ( l + 1 ) ; return ans ; } public static void Main ( String [ ] args ) { int [ ] a = { 1 , 2 , 2 , 3 , 3 , 4 , 5 } ; int n = a . Length ; int k = 3 ; Console . Write ( distinctPrimeSubSeq ( a , n , k ) ) ; } }
Minimize prize count required such that smaller value gets less prize in an adjacent pair | C # implementation to find the minimum prizes required such that adjacent smaller elements gets less number of prizes ; Function to find the minimum number of required such that adjacent smaller elements gets less number of prizes ; Loop to iterate over every elements of the array ; Loop to find the consecutive smaller elements at left ; Loop to find the consecutive smaller elements at right ; Driver Code
using System ; class GFG { static int findMinPrizes ( int [ ] arr , int n ) { int totalPrizes = 0 , j , x , y ; for ( int i = 0 ; i < n ; i ++ ) { x = 1 ; j = i ; while ( j > 0 && arr [ j ] > arr [ j - 1 ] ) { x ++ ; j -- ; } j = i ; y = 1 ; while ( j < n - 1 && arr [ j ] > arr [ j + 1 ] ) { y ++ ; j ++ ; } totalPrizes += Math . Max ( x , y ) ; } Console . Write ( totalPrizes + " STRNEWLINE " ) ; return 0 ; } public static void Main ( String [ ] args ) { int [ ] arr = { 1 , 2 , 2 , 3 } ; int n = arr . Length ; findMinPrizes ( arr , n ) ; } }
Number of ways to split N as sum of K numbers from the given range | C # implementation to count the number of ways to divide N in K groups such that each group has elements in range [ L , R ] ; DP Table ; Function to count the number of ways to divide the number N in K groups such that each group has number of elements in range [ L , R ] ; Base Case ; If N is divides completely into less than k groups ; If the subproblem has been solved , use the value ; Put all possible values greater equal to prev ; Function to count the number of ways to divide the number N ; Initialize DP Table as - 1 ; Driver Code
using System ; class GFG { static int mod = 1000000007 ; static int [ , ] dp = new int [ 1000 , 1000 ] ; static int calculate ( int pos , int left , int k , int L , int R ) { if ( pos == k ) { if ( left == 0 ) return 1 ; else return 0 ; } if ( left == 0 ) return 0 ; if ( dp [ pos , left ] != - 1 ) return dp [ pos , left ] ; int answer = 0 ; for ( int i = L ; i <= R ; i ++ ) { if ( i > left ) break ; answer = ( answer + calculate ( pos + 1 , left - i , k , L , R ) ) % mod ; } return dp [ pos , left ] = answer ; } static int countWaystoDivide ( int n , int k , int L , int R ) { for ( int i = 0 ; i < 1000 ; i ++ ) { for ( int j = 0 ; j < 1000 ; j ++ ) { dp [ i , j ] = - 1 ; } } return calculate ( 0 , n , k , L , R ) ; } public static void Main ( ) { int N = 12 ; int K = 3 ; int L = 1 ; int R = 5 ; Console . Write ( countWaystoDivide ( N , K , L , R ) ) ; } }
Minimum number of squares whose sum equals to given number N | set 2 | C # program to represent N as the sum of minimum square numbers . ; Function for finding minimum square numbers ; A [ i ] of array arr store minimum count of square number to get i ; sqrNum [ i ] store last square number to get i ; Initialize ; Find minimum count of square number for all value 1 to n ; In worst case it will be arr [ i - 1 ] + 1 we use all combination of a [ i - 1 ] and add 1 ; Check for all square number less or equal to i ; if it gives less count then update it ; List v stores optimum square number whose sum give N ; Driver code ; Calling function ; Printing vector
using System ; using System . Collections . Generic ; class GFG { static List < int > minSqrNum ( int n ) { int [ ] arr = new int [ n + 1 ] ; int k = 0 ; int [ ] sqrNum = new int [ n + 1 ] ; List < int > v = new List < int > ( ) ; arr [ 0 ] = 0 ; sqrNum [ 0 ] = 0 ; for ( int i = 1 ; i <= n ; i ++ ) { arr [ i ] = arr [ i - 1 ] + 1 ; sqrNum [ i ] = 1 ; k = 1 ; while ( k * k <= i ) { if ( arr [ i ] > arr [ i - k * k ] + 1 ) { arr [ i ] = arr [ i - k * k ] + 1 ; sqrNum [ i ] = k * k ; } k ++ ; } } while ( n > 0 ) { v . Add ( sqrNum [ n ] ) ; n -= sqrNum [ n ] ; } return v ; } public static void Main ( String [ ] args ) { int n = 10 ; List < int > v ; v = minSqrNum ( n ) ; for ( int i = 0 ; i < v . Count ; i ++ ) { Console . Write ( v [ i ] ) ; if ( i + 1 != v . Count ) Console . Write ( " ▁ + ▁ " ) ; } } }