text
stringlengths
17
3.65k
code
stringlengths
60
5.26k
Number of solutions of n = x + n Γ’Ε  β€’ x | C # implementation of above approach ; Function to find the number of solutions of n = n xor x ; Counter to store the number of solutions found ; Driver code
using System ; class GFG { static int numberOfSolutions ( int n ) { int c = 0 ; for ( int x = 0 ; x <= n ; ++ x ) if ( n == x + ( n ^ x ) ) ++ c ; return c ; } public static void Main ( ) { int n = 3 ; Console . Write ( numberOfSolutions ( n ) ) ; } }
Program to find minimum number of lectures to attend to maintain 75 % | C # Program to find minimum number of lectures to attend to maintain 75 % attendance ; Method to compute minimum lecture ; Formula to compute ; Driver Code
using System ; class GFG { static int minimumLectures ( int m , int n ) { int ans = 0 ; if ( n < ( int ) Math . Ceiling ( 0.75 * m ) ) ans = ( int ) Math . Ceiling ( ( ( 0.75 * m ) - n ) / 0.25 ) ; else ans = 0 ; return ans ; } public static void Main ( ) { int M = 9 , N = 1 ; Console . WriteLine ( minimumLectures ( M , N ) ) ; } }
Count Numbers with N digits which consists of odd number of 0 's | C # program to count numbers with N digits which consists of odd number of 0 's ; Function to count Numbers with N digits which consists of odd number of 0 's ; Driver code
using System ; class GFG { static int countNumbers ( int N ) { return ( int ) ( Math . Pow ( 10 , N ) - Math . Pow ( 8 , N ) ) / 2 ; } public static void Main ( ) { int n = 5 ; Console . WriteLine ( countNumbers ( n ) ) ; } }
Sum of all Primes in a given range using Sieve of Eratosthenes | C # program to find sum of primes in range L to R ; prefix [ i ] is going to store sum of primes till i ( including i ) . ; Function to build the prefix sum array ; Create a boolean array " prime [ 0 . . n ] " . A value in prime [ i ] will finally be false if i is Not a prime , else true . ; If prime [ p ] is not changed , then it is a prime ; Update all multiples of p ; Build prefix array ; Function to return sum of prime in range ; Driver code
using System ; class GFG { static int MAX = 10000 ; static int [ ] prefix = new int [ MAX + 1 ] ; static void buildPrefix ( ) { bool [ ] prime = new bool [ MAX + 1 ] ; for ( int i = 0 ; i < MAX + 1 ; i ++ ) prime [ i ] = true ; for ( int p = 2 ; p * p <= MAX ; p ++ ) { if ( prime [ p ] == true ) { for ( int i = p * 2 ; i <= MAX ; i += p ) prime [ i ] = false ; } } prefix [ 0 ] = prefix [ 1 ] = 0 ; for ( int p = 2 ; p <= MAX ; p ++ ) { prefix [ p ] = prefix [ p - 1 ] ; if ( prime [ p ] == true ) prefix [ p ] += p ; } } static int sumPrimeRange ( int L , int R ) { buildPrefix ( ) ; return prefix [ R ] - prefix [ L - 1 ] ; } public static void Main ( ) { int L = 10 , R = 20 ; Console . WriteLine ( sumPrimeRange ( L , R ) ) ; } }
Sum of the first N terms of the series 5 , 12 , 23 , 38. ... | C # program to find sum of first n terms ; Function to calculate the sum ; Driver code ; number of terms to be included in sum ; find the Sn
using System ; class GFG { static int calculateSum ( int n ) { return 2 * ( n * ( n + 1 ) * ( 2 * n + 1 ) / 6 ) + n * ( n + 1 ) / 2 + 2 * ( n ) ; } public static void Main ( ) { int n = 3 ; Console . WriteLine ( " Sum ▁ = ▁ " + calculateSum ( n ) ) ; } }
Program to find number of solutions in Quadratic Equation | C # Program to find the solutions of specified equations ; Method to check for solutions of equations ; If the expression is greater than 0 , then 2 solutions ; If the expression is equal to 0 , then 2 solutions ; Else no solutions ; Driver Code
using System ; class GFG { static void checkSolution ( int a , int b , int c ) { if ( ( ( b * b ) - ( 4 * a * c ) ) > 0 ) Console . WriteLine ( "2 ▁ solutions " ) ; else if ( ( ( b * b ) - ( 4 * a * c ) ) == 0 ) Console . WriteLine ( "1 ▁ solution " ) ; else Console . WriteLine ( " No ▁ solutions " ) ; } public static void Main ( ) { int a = 2 , b = 5 , c = 2 ; checkSolution ( a , b , c ) ; } }
Program to convert KiloBytes to Bytes and Bits | C # implementation of above program ; Function to calculates the bits ; calculates Bits 1 kilobytes ( s ) = 8192 bits ; Function to calculates the bytes ; calculates Bytes 1 KB = 1024 bytes ; Driver code
using System ; class GFG { static long Bits ( int kilobytes ) { long Bits = 0 ; Bits = kilobytes * 8192 ; return Bits ; } static long Bytes ( int kilobytes ) { long Bytes = 0 ; Bytes = kilobytes * 1024 ; return Bytes ; } static public void Main ( ) { int kilobytes = 1 ; Console . WriteLine ( kilobytes + " ▁ Kilobytes ▁ = ▁ " + Bytes ( kilobytes ) + " ▁ Bytes ▁ and ▁ " + Bits ( kilobytes ) + " ▁ Bits . " ) ; } }
Program to find the Hidden Number | C # Program to find the hidden number ; Driver Code ; Getting the size of array ; Getting the array of size n ; Solution ; Finding sum of the array elements ; Dividing sum by size n ; Print x , if found
using System ; class GFG { public static void Main ( ) { int n = 3 ; int [ ] a = { 1 , 2 , 3 } ; int i = 0 ; long sum = 0 ; for ( i = 0 ; i < n ; i ++ ) { sum += a [ i ] ; } long x = sum / n ; if ( x * n == sum ) Console . WriteLine ( x ) ; else Console . WriteLine ( " - 1" ) ; } }
Find sum of the series ? 3 + ? 12 + ... ... ... upto N terms | C # implementation of above approach ; Function to find the sum ; Apply AP formula ; Driver code ; number of terms
using System ; class GFG { static double findSum ( long n ) { return Math . Sqrt ( 3 ) * ( n * ( n + 1 ) / 2 ) ; } public static void Main ( ) { long n = 10 ; Console . WriteLine ( findSum ( n ) ) ; } }
Find the sum of the series x ( x + y ) + x ^ 2 ( x ^ 2 + y ^ 2 ) + x ^ 3 ( x ^ 3 + y ^ 3 ) + ... + x ^ n ( x ^ n + y ^ n ) | C # program to find the sum of series ; Function to return required sum ; sum of first series ; sum of second series ; Driver code ; function call to print sum
using System ; class GFG { static int sum ( int x , int y , int n ) { int sum1 = ( int ) ( ( Math . Pow ( x , 2 ) * ( Math . Pow ( x , 2 * n ) - 1 ) ) / ( Math . Pow ( x , 2 ) - 1 ) ) ; int sum2 = ( int ) ( ( x * y * ( Math . Pow ( x , n ) * Math . Pow ( y , n ) - 1 ) ) / ( x * y - 1 ) ) ; return sum1 + sum2 ; } public static void Main ( ) { int x = 2 , y = 2 , n = 2 ; Console . Write ( sum ( x , y , n ) ) ; } }
Find any pair with given GCD and LCM | C # program to print any pair with a given gcd G and lcm L ; Function to print the pairs ; Driver Code
using System ; class GFG { static void printPair ( int g , int l ) { Console . Write ( g + " ▁ " + l ) ; } public static void Main ( ) { int g = 3 , l = 12 ; printPair ( g , l ) ; } }
Sum of first n terms of a given series 3 , 6 , 11 , ... . . | C # program to find sum of first n terms ; Function to calculate the sum ; starting number ; Common Ratio ; Common difference ; Driver code ; N th term to be find ; find the Sn
using System ; class GFG { static int calculateSum ( int n ) { int a1 = 1 , a2 = 2 ; int r = 2 ; int d = 1 ; return ( n ) * ( 2 * a1 + ( n - 1 ) * d ) / 2 + a2 * ( int ) ( Math . Pow ( r , n ) - 1 ) / ( r - 1 ) ; } public static void Main ( ) { int n = 5 ; Console . WriteLine ( " Sum ▁ = ▁ " + calculateSum ( n ) ) ; } }
Maximum of sum and product of digits until number is reduced to a single digit | C # implementation of above approach ; Function to sum the digits until it becomes a single digit ; Function to product the digits until it becomes a single digit ; Loop to do sum while sum is not less than or equal to 9 ; Function to find the maximum among repeated sum and repeated product ; Driver code
using System ; class GFG { public static long repeatedSum ( long n ) { if ( n == 0 ) return 0 ; return ( n % 9 == 0 ) ? 9 : ( n % 9 ) ; } public static long repeatedProduct ( long n ) { long prod = 1 ; while ( n > 0 prod > 9 ) { if ( n == 0 ) { n = prod ; prod = 1 ; } prod *= n % 10 ; n /= 10 ; } return prod ; } public static long maxSumProduct ( long N ) { if ( N < 10 ) return N ; return Math . Max ( repeatedSum ( N ) , repeatedProduct ( N ) ) ; } public static void Main ( ) { long n = 631 ; Console . WriteLine ( maxSumProduct ( n ) ) ; } }
Count numbers with exactly K non | C # program to count the numbers having exactly K non - zero digits and sum of digits are odd and distinct . ; To store digits of N ; visited map ; DP Table ; Push all the digits of N into digits vector ; Function returns the count ; If desired number is formed whose sum is odd ; If it is not present in map , mark it as true and return 1 ; Sum is present in map already ; Desired result not found ; If that state is already calculated just return that state value ; Upper limit ; To store the count of desired numbers ; If k is non - zero , i ranges from 0 to j else [ 1 , j ] ; If current digit is 0 , decrement k and recurse sum is not changed as we are just adding 0 that makes no difference ; If i is non zero , then k remains unchanged and value is added to sum ; Memoize and return ; Driver code ; K is the number of exact non - zero elements to have in number ; break N into its digits ; We keep record of 0 s we need to place in the number
using System ; using System . Collections . Generic ; class GFG { static List < int > digits = new List < int > ( ) ; static bool [ ] vis = new bool [ 170 ] ; static int [ , , , ] dp = new int [ 19 , 19 , 2 , 170 ] ; static void ConvertIntoDigit ( int n ) { while ( n > 0 ) { int dig = n % 10 ; digits . Add ( dig ) ; n /= 10 ; } digits . Reverse ( ) ; } static int solve ( int idx , int k , int tight , int sum ) { if ( idx == digits . Count && k == 0 && sum % 2 == 1 ) { if ( ! vis [ sum ] ) { vis [ sum ] = true ; return 1 ; } return 0 ; } if ( idx > digits . Count ) { return 0 ; } if ( dp [ idx , k , tight , sum ] > 0 ) { return dp [ idx , k , tight , sum ] ; } int j ; if ( idx < digits . Count && tight == 0 ) { j = digits [ idx ] ; } else { j = 9 ; } int cnt = 0 ; for ( int i = ( k > 0 ? 0 : 1 ) ; i <= j ; i ++ ) { int newtight = tight ; if ( i < j ) { newtight = 1 ; } if ( i == 0 ) cnt += solve ( idx + 1 , k - 1 , newtight , sum ) ; else cnt += solve ( idx + 1 , k , newtight , sum + i ) ; } return dp [ idx , k , tight , sum ] = cnt ; } public static void Main ( String [ ] args ) { int N , k ; N = 169 ; k = 2 ; ConvertIntoDigit ( N ) ; k = digits . Count - k ; Console . Write ( solve ( 0 , k , 0 , 0 ) ) ; } }
Count of subsets of integers from 1 to N having no adjacent elements | C # code to count subsets not containing adjacent elements from 1 to N ; Function to count subsets ; Driver code
using System ; class GFG { static int countSubsets ( int N ) { if ( N <= 2 ) return N ; if ( N == 3 ) return 2 ; int [ ] DP = new int [ N + 1 ] ; DP [ 0 ] = 0 ; DP [ 1 ] = 1 ; DP [ 2 ] = 2 ; DP [ 3 ] = 2 ; for ( int i = 4 ; i <= N ; i ++ ) { DP [ i ] = DP [ i - 2 ] + DP [ i - 3 ] ; } return DP [ N ] ; } public static void Main ( String [ ] args ) { int N = 20 ; Console . Write ( countSubsets ( N ) ) ; } }
Count the number of ordered sets not containing consecutive numbers | C # program to count the number of ordered sets not containing consecutive numbers ; DP table ; Function to calculate the count of ordered set for a given size ; Base cases ; If subproblem has been soved before ; Store and return answer to this subproblem ; Function returns the count of all ordered sets ; Prestore the factorial value ; Initialise the dp table ; Iterate all ordered set sizes and find the count for each one maximum ordered set size will be smaller than N as all elements are distinct and non consecutive . ; Multiply ny size ! for all the arrangements because sets are ordered . ; Add to total answer ; Driver code
using System ; class GFG { static int [ , ] dp = new int [ 500 , 500 ] ; static int CountSets ( int x , int pos ) { if ( x <= 0 ) { if ( pos == 0 ) return 1 ; else return 0 ; } if ( pos == 0 ) return 1 ; if ( dp [ x , pos ] != - 1 ) return dp [ x , pos ] ; int answer = CountSets ( x - 1 , pos ) + CountSets ( x - 2 , pos - 1 ) ; return dp [ x , pos ] = answer ; } static int CountOrderedSets ( int n ) { int [ ] factorial = new int [ 10000 ] ; factorial [ 0 ] = 1 ; for ( int i = 1 ; i < 10000 ; i ++ ) factorial [ i ] = factorial [ i - 1 ] * i ; int answer = 0 ; for ( int i = 0 ; i < 500 ; i ++ ) { for ( int j = 0 ; j < 500 ; j ++ ) { dp [ i , j ] = - 1 ; } } for ( int i = 1 ; i <= n ; i ++ ) { int sets = CountSets ( n , i ) * factorial [ i ] ; answer = answer + sets ; } return answer ; } public static void Main ( String [ ] args ) { int N = 3 ; Console . Write ( CountOrderedSets ( N ) ) ; } }
Count the Arithmetic sequences in the Array of size at least 3 | C # program to find all arithmetic sequences of size atleast 3 ; Function to find all arithmetic sequences of size atleast 3 ; If array size is less than 3 ; Finding arithmetic subarray length ; To store all arithmetic subarray of length at least 3 ; Check if current element makes arithmetic sequence with previous two elements ; Begin with a new element for new arithmetic sequences ; Accumulate result in till i . ; Return readonly count ; Driver code ; Function to find arithmetic sequences
using System ; class GFG { static int numberOfArithmeticSequences ( int [ ] L , int N ) { if ( N <= 2 ) return 0 ; int count = 0 ; int res = 0 ; for ( int i = 2 ; i < N ; ++ i ) { if ( L [ i ] - L [ i - 1 ] == L [ i - 1 ] - L [ i - 2 ] ) { ++ count ; } else { count = 0 ; } res += count ; } return res ; } public static void Main ( String [ ] args ) { int [ ] L = { 1 , 3 , 5 , 6 , 7 , 8 } ; int N = L . Length ; Console . Write ( numberOfArithmeticSequences ( L , N ) ) ; } }
Count triplet of indices ( i , j , k ) such that XOR of elements between [ i , j ) equals [ j , k ] | C # program to count the Number of triplets in array having subarray XOR equal ; Function return the count of triplets having subarray XOR equal ; XOR value till i ; Count and ways array as defined above ; Using the formula stated ; Increase the frequency of x ; Add i + 1 to ways [ x ] for upcoming indices ; Driver code
using System ; class GFG { static int CountOfTriplets ( int [ ] a , int n ) { int answer = 0 ; int x = 0 ; int [ ] count = new int [ 100005 ] ; int [ ] ways = new int [ 100005 ] ; for ( int i = 0 ; i < n ; i ++ ) { x ^= a [ i ] ; answer += count [ x ] * i - ways [ x ] ; count [ x ] ++ ; ways [ x ] += ( i + 1 ) ; } return answer ; } public static void Main ( String [ ] args ) { int [ ] Arr = { 3 , 6 , 12 , 8 , 6 , 2 , 1 , 5 } ; int N = Arr . Length ; Console . Write ( CountOfTriplets ( Arr , N ) ) ; } }
Count of subarrays of an Array having all unique digits | C # program to find the count of subarrays of an Array having all unique digits ; Dynamic programming table ; Function to obtain the mask for any integer ; Function to count the number of ways ; Subarray must not be empty ; If subproblem has been solved ; Excluding this element in the subarray ; If there are no common digits then only this element can be included ; Calculate the new mask if this element is included ; Store and return the answer ; Function to find the count of subarray with all digits unique ; initializing dp ; Driver code
using System ; public class GFG { static int [ , ] dp = new int [ 5000 , ( 1 << 10 ) + 5 ] ; static int getmask ( int val ) { int mask = 0 ; if ( val == 0 ) return 1 ; while ( val > 0 ) { int d = val % 10 ; mask |= ( 1 << d ) ; val /= 10 ; } return mask ; } static int countWays ( int pos , int mask , int [ ] a , int n ) { if ( pos == n ) return ( mask > 0 ? 1 : 0 ) ; if ( dp [ pos , mask ] != - 1 ) return dp [ pos , mask ] ; int count = 0 ; count = count + countWays ( pos + 1 , mask , a , n ) ; if ( ( getmask ( a [ pos ] ) & mask ) == 0 ) { int new_mask = ( mask | ( getmask ( a [ pos ] ) ) ) ; count = count + countWays ( pos + 1 , new_mask , a , n ) ; } return dp [ pos , mask ] = count ; } static int numberOfSubarrays ( int [ ] a , int n ) { for ( int i = 0 ; i < 5000 ; i ++ ) { for ( int j = 0 ; j < ( 1 << 10 ) + 5 ; j ++ ) { dp [ i , j ] = - 1 ; } } return countWays ( 0 , 0 , a , n ) ; } public static void Main ( String [ ] args ) { int N = 4 ; int [ ] A = { 1 , 12 , 23 , 34 } ; Console . Write ( numberOfSubarrays ( A , N ) ) ; } }
Count of Fibonacci paths in a Binary tree | C # program to count all of Fibonacci paths in a Binary tree ; List to store the fibonacci series ; Binary Tree Node ; Function to create a new tree node ; Function to find the height of the given tree ; Function to make fibonacci series upto n terms ; Preorder Utility function to count exponent path in a given Binary tree ; Base Condition , when node pointer becomes null or node value is not a number of Math . Pow ( x , y ) ; Increment count when encounter leaf node ; Left recursive call save the value of count ; Right recursive call and return value of count ; Function to find whether fibonacci path exists or not ; To find the height ; Making fibonacci series upto ht terms ; Driver code ; Create binary tree ; Function Call
using System ; using System . Collections . Generic ; class GFG { static List < int > fib = new List < int > ( ) ; class node { public node left ; public int data ; public node right ; } ; static node newNode ( int data ) { node temp = new node ( ) ; temp . data = data ; temp . left = null ; temp . right = null ; return temp ; } static int height ( node root ) { if ( root == null ) return 0 ; return ( Math . Max ( height ( root . left ) , height ( root . right ) ) + 1 ) ; } static void FibonacciSeries ( int n ) { fib . Add ( 0 ) ; fib . Add ( 1 ) ; for ( int i = 2 ; i < n ; i ++ ) fib . Add ( fib [ i - 1 ] + fib [ i - 2 ] ) ; } static int CountPathUtil ( node root , int i , int count ) { if ( root == null || ! ( fib [ i ] == root . data ) ) { return count ; } if ( root . left != null && root . right != null ) { count ++ ; } count = CountPathUtil ( root . left , i + 1 , count ) ; return CountPathUtil ( root . right , i + 1 , count ) ; } static void CountPath ( node root ) { int ht = height ( root ) ; FibonacciSeries ( ht ) ; Console . Write ( CountPathUtil ( root , 0 , 0 ) ) ; } public static void Main ( String [ ] args ) { node root = newNode ( 0 ) ; root . left = newNode ( 1 ) ; root . right = newNode ( 1 ) ; root . left . left = newNode ( 1 ) ; root . left . right = newNode ( 4 ) ; root . right . right = newNode ( 1 ) ; root . right . right . left = newNode ( 2 ) ; CountPath ( root ) ; } }
Numbers with a Fibonacci difference between Sum of digits at even and odd positions in a given range | C # program to count the numbers in the range having the difference between the sum of digits at even and odd positions as a Fibonacci Number ; To store all the Fibonacci numbers ; Function to generate Fibonacci numbers upto 100 ; Adding the first two Fibonacci numbers in the set ; Computing the remaining Fibonacci numbers using the first two Fibonacci numbers ; Function to return the count of required numbers from 0 to num ; Base Case ; Check if the difference is equal to any fibonacci number ; If this result is already computed simply return it ; Maximum limit upto which we can place digit . If tight is 1 , means number has already become smaller so we can place any digit , otherwise num [ pos ] ; If the current position is odd add it to currOdd , otherwise to currEven ; Function to convert x into its digit vector and uses count ( ) function to return the required count ; Initialize dp ; Driver Code ; Generate fibonacci numbers
using System ; using System . Collections . Generic ; public class GFG { static int M = 18 ; static int a , b ; static int [ , , , ] dp = new int [ M , 90 , 90 , 2 ] ; static HashSet < int > fib = new HashSet < int > ( ) ; static void fibonacci ( ) { int prev = 0 , curr = 1 ; fib . Add ( prev ) ; fib . Add ( curr ) ; while ( curr <= 100 ) { int temp = curr + prev ; fib . Add ( temp ) ; prev = curr ; curr = temp ; } } static int count ( int pos , int even , int odd , int tight , List < int > num ) { if ( pos == num . Count ) { if ( num . Count % 2 == 1 ) { odd = odd + even ; even = odd - even ; odd = odd - even ; } int d = even - odd ; if ( fib . Contains ( d ) ) return 1 ; return 0 ; } if ( dp [ pos , even , odd , tight ] != - 1 ) return dp [ pos , even , odd , tight ] ; int ans = 0 ; int limit = ( tight == 1 ? 9 : num [ pos ] ) ; for ( int d = 0 ; d <= limit ; d ++ ) { int currF = tight , currEven = even ; int currOdd = odd ; if ( d < num [ pos ] ) currF = 1 ; if ( pos % 2 == 1 ) currOdd += d ; else currEven += d ; ans += count ( pos + 1 , currEven , currOdd , currF , num ) ; } return dp [ pos , even , odd , tight ] = ans ; } static int solve ( int x ) { List < int > num = new List < int > ( ) ; while ( x > 0 ) { num . Add ( x % 10 ) ; x /= 10 ; } num . Reverse ( ) ; for ( int i = 0 ; i < M ; i ++ ) { for ( int j = 0 ; j < 90 ; j ++ ) { for ( int l = 0 ; l < 90 ; l ++ ) { for ( int k = 0 ; k < 2 ; k ++ ) { dp [ i , j , l , k ] = - 1 ; } } } } return count ( 0 , 0 , 0 , 0 , num ) ; } public static void Main ( String [ ] args ) { fibonacci ( ) ; int L = 1 , R = 50 ; Console . Write ( solve ( R ) - solve ( L - 1 ) + " STRNEWLINE " ) ; L = 50 ; R = 100 ; Console . Write ( solve ( R ) - solve ( L - 1 ) + " STRNEWLINE " ) ; } }
Count maximum occurrence of subsequence in string such that indices in subsequence is in A . P . | C # implementation to find the maximum occurrence of the subsequence such that the indices of characters are in arithmetic progression ; Function to find the maximum occurrence of the subsequence such that the indices of characters are in arithmetic progression ; Frequency for characters ; Loop to count the occurrence of ith character before jth character in the given String ; Increase the frequency of s [ i ] or c of String ; Maximum occurrence of subsequence of length 1 in given String ; Maximum occurrence of subsequence of length 2 in given String ; Driver Code
using System ; class GFG { static int maximumOccurrence ( string s ) { int n = s . Length ; int [ ] freq = new int [ 26 ] ; int [ , ] dp = new int [ 26 , 26 ] ; for ( int i = 0 ; i < n ; i ++ ) { int x = ( s [ i ] - ' a ' ) ; for ( int j = 0 ; j < 26 ; j ++ ) dp [ x , j ] += freq [ j ] ; freq [ x ] ++ ; } int answer = int . MinValue ; for ( int i = 0 ; i < 26 ; i ++ ) answer = Math . Max ( answer , freq [ i ] ) ; for ( int i = 0 ; i < 26 ; i ++ ) { for ( int j = 0 ; j < 26 ; j ++ ) { answer = Math . Max ( answer , dp [ i , j ] ) ; } } return answer ; } public static void Main ( string [ ] args ) { string s = " xxxyy " ; Console . Write ( maximumOccurrence ( s ) ) ; } }
Count the numbers with N digits and whose suffix is divisible by K | C # implementation to Count the numbers with N digits and whose suffix is divisible by K ; Suffix of length pos with remainder rem and Z representing whether the suffix has a non zero digit until now ; Base case ; If count of digits is less than n ; Placing all possible digits in remaining positions ; If remainder non zero and suffix has n digits ; If the subproblem is already solved ; Placing all digits at MSB of suffix and increasing it 's length by 1 ; Non zero digit is placed ; Store and return the solution to this subproblem ; Function to Count the numbers with N digits and whose suffix is divisible by K ; Since we need powers of 10 for counting , it 's better to pre store them along with their modulo with 1e9 + 7 for counting ; Since at each recursive step we increase the suffix length by 1 by placing digits at its leftmost position , we need powers of 10 modded with k , in order to fpos the new remainder efficiently ; Initialising dp table values - 1 represents subproblem hasn 't been solved yet ; Driver Code
using System ; class GFG { static int mod = 1000000007 ; static int [ , , ] dp = new int [ 1005 , 105 , 2 ] ; static int [ ] powers = new int [ 1005 ] ; static int [ ] powersModk = new int [ 1005 ] ; static int calculate ( int pos , int rem , int z , int k , int n ) { if ( rem == 0 && z != 0 ) { if ( pos != n ) return ( powers [ n - pos - 1 ] * 9 ) % mod ; else return 1 ; } if ( pos == n ) return 0 ; if ( dp [ pos , rem , z ] != - 1 ) return dp [ pos , rem , z ] ; int count = 0 ; for ( int i = 0 ; i < 10 ; i ++ ) { if ( i == 0 ) count = ( count + ( calculate ( pos + 1 , ( rem + ( i * powersModk [ pos ] ) % k ) % k , z , k , n ) ) ) % mod ; else count = ( count + ( calculate ( pos + 1 , ( rem + ( i * powersModk [ pos ] ) % k ) % k , 1 , k , n ) ) ) % mod ; } return dp [ pos , rem , z ] = count ; } static int countNumbers ( int n , int k ) { int st = 1 ; int i ; for ( i = 0 ; i <= n ; i ++ ) { powers [ i ] = st ; st *= 10 ; st %= mod ; } st = 1 ; for ( i = 0 ; i <= n ; i ++ ) { powersModk [ i ] = st ; st *= 10 ; st %= mod ; } for ( i = 0 ; i < 1005 ; i ++ ) { for ( int j = 0 ; j < 105 ; j ++ ) { for ( int l = 0 ; l < 2 ; l ++ ) dp [ i , j , l ] = - 1 ; } } return calculate ( 0 , 0 , 0 , k , n ) ; } public static void Main ( String [ ] args ) { int N = 2 ; int K = 2 ; Console . Write ( countNumbers ( N , K ) ) ; } }
Find Maximum Length Of A Square Submatrix Having Sum Of Elements At | C # implementation of the above approach ; Function to return maximum length of square submatrix having sum of elements at - most K ; Matrix to store prefix sum ; Current maximum length ; Variable for storing maximum length of square ; Calculating prefix sum ; Checking whether there exits square with length cur_max + 1 or not ; Returning the maximum length ; Driver code
using System ; class GFG { public static int maxLengthSquare ( int row , int column , int [ , ] arr , int k ) { int [ , ] sum = new int [ row + 1 , column + 1 ] ; int cur_max = 1 ; int max = 0 ; for ( int i = 1 ; i <= row ; i ++ ) { for ( int j = 1 ; j <= column ; j ++ ) { sum [ i , j ] = sum [ i - 1 , j ] + sum [ i , j - 1 ] + arr [ i - 1 , j - 1 ] - sum [ i - 1 , j - 1 ] ; if ( i >= cur_max && j >= cur_max && sum [ i , j ] - sum [ i - cur_max , j ] - sum [ i , j - cur_max ] + sum [ i - cur_max , j - cur_max ] <= k ) { max = cur_max ++ ; } } } return max ; } public static void Main ( ) { int row = 4 , column = 4 ; int [ , ] matrix = { { 1 , 1 , 1 , 1 } , { 1 , 0 , 0 , 0 } , { 1 , 0 , 0 , 0 } , { 1 , 0 , 0 , 0 } } ; int k = 6 ; int ans = maxLengthSquare ( row , column , matrix , k ) ; Console . WriteLine ( ans ) ; } }
Sum of all numbers formed having 4 atmost X times , 5 atmost Y times and 6 atmost Z times | C # program to find sum of all numbers formed having 4 atmost X times , 5 atmost Y times and 6 atmost Z times ; exactsum [ i ] [ j ] [ k ] stores the sum of all the numbers having exact i 4 ' s , ▁ j ▁ 5' s and k 6 's ; exactnum [ i ] [ j ] [ k ] stores numbers of numbers having exact i 4 ' s , ▁ j ▁ 5' s and k 6 's ; Utility function to calculate the sum for x 4 ' s , ▁ y ▁ 5' s and z 6 's ; Computing exactsum [ i , j , k ] as explained above ; Driver code
using System ; class GFG { static int N = 101 ; static int mod = ( int ) 1e9 + 7 ; static int [ , , ] exactsum = new int [ N , N , N ] ; static int [ , , ] exactnum = new int [ N , N , N ] ; static int getSum ( int x , int y , int z ) { int ans = 0 ; exactnum [ 0 , 0 , 0 ] = 1 ; for ( int i = 0 ; i <= x ; ++ i ) { for ( int j = 0 ; j <= y ; ++ j ) { for ( int k = 0 ; k <= z ; ++ k ) { if ( i > 0 ) { exactsum [ i , j , k ] += ( exactsum [ i - 1 , j , k ] * 10 + 4 * exactnum [ i - 1 , j , k ] ) % mod ; exactnum [ i , j , k ] += exactnum [ i - 1 , j , k ] % mod ; } if ( j > 0 ) { exactsum [ i , j , k ] += ( exactsum [ i , j - 1 , k ] * 10 + 5 * exactnum [ i , j - 1 , k ] ) % mod ; exactnum [ i , j , k ] += exactnum [ i , j - 1 , k ] % mod ; } if ( k > 0 ) { exactsum [ i , j , k ] += ( exactsum [ i , j , k - 1 ] * 10 + 6 * exactnum [ i , j , k - 1 ] ) % mod ; exactnum [ i , j , k ] += exactnum [ i , j , k - 1 ] % mod ; } ans += exactsum [ i , j , k ] % mod ; ans %= mod ; } } } return ans ; } public static void Main ( ) { int x = 1 , y = 1 , z = 1 ; Console . WriteLine ( getSum ( x , y , z ) % mod ) ; } }
Maximum value obtained by performing given operations in an Array | C # implementation of the above approach ; A function to calculate the maximum value ; basecases ; Loop to iterate and add the max value in the dp array ; Driver Code
using System ; class GFG { static void findMax ( int [ ] a , int n ) { int [ , ] dp = new int [ n , 2 ] ; int i , j ; for ( i = 0 ; i < n ; i ++ ) for ( j = 0 ; j < 2 ; j ++ ) dp [ i , j ] = 0 ; dp [ 0 , 0 ] = a [ 0 ] + a [ 1 ] ; dp [ 0 , 1 ] = a [ 0 ] * a [ 1 ] ; for ( i = 1 ; i <= n - 2 ; i ++ ) { dp [ i , 0 ] = Math . Max ( dp [ i - 1 , 0 ] , dp [ i - 1 , 1 ] ) + a [ i + 1 ] ; dp [ i , 1 ] = dp [ i - 1 , 0 ] - a [ i ] + a [ i ] * a [ i + 1 ] ; } Console . WriteLine ( Math . Max ( dp [ n - 2 , 0 ] , dp [ n - 2 , 1 ] ) ) ; } public static void Main ( ) { int [ ] arr = { 5 , - 1 , - 5 , - 3 , 2 , 9 , - 4 } ; findMax ( arr , 7 ) ; } }
Optimal strategy for a Game with modifications | C # implementation of the above approach ; Function to return sum of subarray from l to r ; calculate sum by a loop from l to r ; dp to store the values of sub problems ; if length of the array is less than k return the sum ; if the value is previously calculated ; else calculate the value ; select all the sub array of length len_r ; get the sum of that sub array ; check if it is the maximum or not ; store it in the table ; Driver code
using System ; class GFG { static int sum ( int [ ] arr , int l , int r ) { int s = 0 ; for ( int i = l ; i <= r ; i ++ ) { s += arr [ i ] ; } return s ; } static int [ , , ] dp = new int [ 101 , 101 , 101 ] ; static int solve ( int [ ] arr , int l , int r , int k ) { if ( r - l + 1 <= k ) return sum ( arr , l , r ) ; if ( dp [ l , r , k ] != 0 ) return dp [ l , r , k ] ; int sum_ = sum ( arr , l , r ) ; int len_r = ( r - l + 1 ) - k ; int len = ( r - l + 1 ) ; int ans = 0 ; for ( int i = 0 ; i < len - len_r + 1 ; i ++ ) { int sum_sub = sum ( arr , i + l , i + l + len_r - 1 ) ; ans = Math . Max ( ans , ( sum_ - sum_sub ) + ( sum_sub - solve ( arr , i + l , i + l + len_r - 1 , k ) ) ) ; } dp [ l , r , k ] = ans ; return ans ; } public static void Main ( ) { int [ ] arr = { 10 , 15 , 20 , 9 , 2 , 5 } ; int k = 2 ; int n = arr . Length ; Console . WriteLine ( solve ( arr , 0 , n - 1 , k ) ) ; } }
Find the minimum difference path from ( 0 , 0 ) to ( N | C # implementation of the approach ; Function to return the minimum difference path from ( 0 , 0 ) to ( N - 1 , M - 1 ) ; Terminating case ; Base case ; If it is already visited ; Recursive calls ; Return the value ; Driver code ; Function call
using System ; class GFG { static int MAXI = 50 ; static int [ , , ] dp = new int [ MAXI , MAXI , MAXI * MAXI ] ; static int n , m ; static int INT_MAX = int . MaxValue ; static int minDifference ( int x , int y , int k , int [ , ] b , int [ , ] c ) { int diff = 0 ; if ( x >= n y >= m ) return INT_MAX ; if ( x == n - 1 && y == m - 1 ) { diff = b [ x , y ] - c [ x , y ] ; return Math . Min ( Math . Abs ( k - diff ) , Math . Abs ( k + diff ) ) ; } int ans = dp [ x , y , k ] ; if ( ans != - 1 ) return ans ; ans = INT_MAX ; diff = b [ x , y ] - c [ x , y ] ; ans = Math . Min ( ans , minDifference ( x + 1 , y , Math . Abs ( k + diff ) , b , c ) ) ; ans = Math . Min ( ans , minDifference ( x , y + 1 , Math . Abs ( k + diff ) , b , c ) ) ; ans = Math . Min ( ans , minDifference ( x + 1 , y , Math . Abs ( k - diff ) , b , c ) ) ; ans = Math . Min ( ans , minDifference ( x , y + 1 , Math . Abs ( k - diff ) , b , c ) ) ; return ans ; } public static void Main ( ) { n = 2 ; m = 2 ; int [ , ] b = { { 1 , 4 } , { 2 , 4 } } ; int [ , ] c = { { 3 , 2 } , { 3 , 1 } } ; for ( int i = 0 ; i < MAXI ; i ++ ) { for ( int j = 0 ; j < MAXI ; j ++ ) { for ( int k = 0 ; k < MAXI * MAXI ; k ++ ) { dp [ i , j , k ] = - 1 ; } } } Console . WriteLine ( minDifference ( 0 , 0 , 0 , b , c ) ) ; } }
Longest subsequence having difference atmost K | C # program for the above approach ; Function to find the longest Special Sequence ; Creating a list with all 0 's of size equal to the length of String ; Supporting list with all 0 's of size 26 since the given String consists of only lower case alphabets ; Converting the ascii value to list indices ; Determining the lower bound ; Determining the upper bound ; Filling the dp array with values ; Filling the max_length array with max length of subsequence till now ; return the max length of subsequence ; Driver Code
using System ; class GFG { static int longest_subseq ( int n , int k , String s ) { int [ ] dp = new int [ n ] ; int [ ] max_length = new int [ 26 ] ; for ( int i = 0 ; i < n ; i ++ ) { int curr = s [ i ] - ' a ' ; int lower = Math . Max ( 0 , curr - k ) ; int upper = Math . Min ( 25 , curr + k ) ; for ( int j = lower ; j < upper + 1 ; j ++ ) { dp [ i ] = Math . Max ( dp [ i ] , max_length [ j ] + 1 ) ; } max_length [ curr ] = Math . Max ( dp [ i ] , max_length [ curr ] ) ; } int ans = 0 ; foreach ( int i in dp ) ans = Math . Max ( i , ans ) ; return ans ; } public static void Main ( String [ ] args ) { String s = " geeksforgeeks " ; int n = s . Length ; int k = 3 ; Console . Write ( longest_subseq ( n , k , s ) ) ; } }
Maximum sum subarray after altering the array | C # implementation of the approach ; Function that returns true if all the array element are <= 0 ; If any element is non - negative ; Function to return the vector representing the right to left Kadane array as described in the approach ; Function to return the prefix_sum vector ; Function to return the maximum sum subarray ; Function to get the maximum sum subarray in the modified array ; kadane_r_to_l [ i ] will store the maximum subarray sum for thre subarray arr [ i ... N - 1 ] ; Get the prefix sum array ; To get max_prefix_sum_at_any_index ; Summation of both gives the maximum subarray sum after applying the operation ; Function to return the maximum subarray sum after performing the given operation at most once ; If all element are negative then return the maximum element ; Maximum subarray sum without performing any operation ; Maximum subarray sum after performing the operations of first type ; Reversing the array to use the same existing function for operations of the second type ; Driver code
using System . Collections . Generic ; using System ; class GFG { static bool areAllNegative ( int [ ] arr ) { int n = arr . Length ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] > 0 ) return false ; } return true ; } static int [ ] getRightToLeftKadane ( int [ ] arr ) { int max_so_far = 0 , max_ending_here = 0 ; int size = arr . Length ; int [ ] new_arr = new int [ size ] ; for ( int i = 0 ; i < size ; i ++ ) new_arr [ i ] = arr [ i ] ; for ( int i = size - 1 ; i >= 0 ; i -- ) { max_ending_here = max_ending_here + new_arr [ i ] ; if ( max_ending_here < 0 ) max_ending_here = 0 ; else if ( max_so_far < max_ending_here ) max_so_far = max_ending_here ; new_arr [ i ] = max_so_far ; } return new_arr ; } static int [ ] getPrefixSum ( int [ ] arr ) { int n = arr . Length ; int [ ] new_arr = new int [ n ] ; for ( int i = 0 ; i < n ; i ++ ) new_arr [ i ] = arr [ i ] ; for ( int i = 1 ; i < n ; i ++ ) new_arr [ i ] = new_arr [ i - 1 ] + new_arr [ i ] ; return new_arr ; } static int maxSumSubArr ( int [ ] a ) { int max_so_far = 0 , max_ending_here = 0 ; int n = a . Length ; for ( int i = 0 ; i < n ; i ++ ) { max_ending_here = max_ending_here + a [ i ] ; if ( max_ending_here < 0 ) max_ending_here = 0 ; else if ( max_so_far < max_ending_here ) max_so_far = max_ending_here ; } return max_so_far ; } static int maxSumSubWithOp ( int [ ] arr ) { int [ ] kadane_r_to_l = getRightToLeftKadane ( arr ) ; int size = arr . Length ; int [ ] prefixSum = getPrefixSum ( arr ) ; for ( int i = 1 ; i < size ; i ++ ) { prefixSum [ i ] = Math . Max ( prefixSum [ i - 1 ] , prefixSum [ i ] ) ; } int max_subarray_sum = 0 ; for ( int i = 0 ; i < size - 1 ; i ++ ) { max_subarray_sum = Math . Max ( max_subarray_sum , prefixSum [ i ] + kadane_r_to_l [ i + 1 ] ) ; } return max_subarray_sum ; } static int maxSum ( int [ ] arr , int size ) { if ( areAllNegative ( arr ) ) { int mx = - 1000000000 ; for ( int i = 0 ; i < size ; i ++ ) { if ( arr [ i ] > mx ) mx = arr [ i ] ; } return mx ; } int resSum = maxSumSubArr ( arr ) ; resSum = Math . Max ( resSum , maxSumSubWithOp ( arr ) ) ; int [ ] reverse_arr = new int [ size ] ; for ( int i = 0 ; i < size ; i ++ ) reverse_arr [ size - 1 - i ] = arr [ i ] ; resSum = Math . Max ( resSum , maxSumSubWithOp ( reverse_arr ) ) ; return resSum ; } public static void Main ( ) { int [ ] arr = { - 9 , 21 , 24 , 24 , - 51 , - 6 , 17 , - 42 , - 39 , 33 } ; int size = arr . Length ; Console . Write ( maxSum ( arr , size ) ) ; } }
Maximum possible array sum after performing the given operation | C # implementation of the approach ; Function to return the maximum possible sum after performing the given operation ; Dp vector to store the answer ; Base value ; Return the maximum sum ; Driver code
using System ; class GFG { static int max_sum ( int [ ] a , int n ) { int [ , ] dp = new int [ n + 1 , 2 ] ; dp [ 0 , 0 ] = 0 ; dp [ 0 , 1 ] = - 999999 ; for ( int i = 0 ; i <= n - 1 ; i ++ ) { dp [ i + 1 , 0 ] = Math . Max ( dp [ i , 0 ] + a [ i ] , dp [ i , 1 ] - a [ i ] ) ; dp [ i + 1 , 1 ] = Math . Max ( dp [ i , 0 ] - a [ i ] , dp [ i , 1 ] + a [ i ] ) ; } return dp [ n , 0 ] ; } public static void Main ( String [ ] args ) { int [ ] a = { - 10 , 5 , - 4 } ; int n = a . Length ; Console . WriteLine ( max_sum ( a , n ) ) ; } }
Find the number of ways to reach Kth step in stair case | C # implementation of the approach ; Function to return the number of ways to reach the kth step ; Create the dp array ; Broken steps ; Calculate the number of ways for the rest of the positions ; If it is a blocked position ; Number of ways to get to the ith step ; Return the required answer ; Driver code
using System ; class GFG { static readonly int MOD = 1000000007 ; static int number_of_ways ( int [ ] arr , int n , int k ) { if ( k == 1 ) return 1 ; int [ ] dp = new int [ k + 1 ] ; int i ; for ( i = 0 ; i < k + 1 ; i ++ ) dp [ i ] = - 1 ; for ( i = 0 ; i < n ; i ++ ) dp [ arr [ i ] ] = 0 ; dp [ 0 ] = 1 ; dp [ 1 ] = ( dp [ 1 ] == - 1 ) ? 1 : dp [ 1 ] ; for ( i = 2 ; i <= k ; ++ i ) { if ( dp [ i ] == 0 ) continue ; dp [ i ] = dp [ i - 1 ] + dp [ i - 2 ] ; dp [ i ] %= MOD ; } return dp [ k ] ; } public static void Main ( String [ ] args ) { int [ ] arr = { 3 } ; int n = arr . Length ; int k = 6 ; Console . WriteLine ( number_of_ways ( arr , n , k ) ) ; } }
Minimum number of coins that can generate all the values in the given range | C # program to find minimum number of coins ; Function to find minimum number of coins ; Driver code
using System ; class GFG { static int findCount ( int n ) { return ( int ) ( Math . Log ( n ) / Math . Log ( 2 ) ) + 1 ; } public static void Main ( ) { int N = 10 ; Console . Write ( findCount ( N ) ) ; } }
Calculate the number of set bits for every number from 0 to N | C # implementation of the approach ; Function to find the count of set bits in all the integers from 0 to n ; Driver code
using System ; class GFG { static int count ( int n ) { int count = 0 ; while ( n > 0 ) { count += n & 1 ; n >>= 1 ; } return count ; } static void findSetBits ( int n ) { for ( int i = 0 ; i <= n ; i ++ ) Console . Write ( count ( i ) + " ▁ " ) ; } public static void Main ( String [ ] args ) { int n = 5 ; findSetBits ( n ) ; } }
Count number of ways to arrange first N numbers | C # implementation of the above approach ; Function to return the count of required arrangements ; Create a vector ; Store numbers from 1 to n ; To store the count of ways ; Generate all the permutations using next_permutation in STL ; Initialize flag to true if first element is 1 else false ; Checking if the current permutation satisfies the given conditions ; If the current permutation is invalid then set the flag to false ; If valid arrangement ; Generate the next permutation ; ; Driver code
using System ; using System . Collections . Generic ; class GFG { static int countWays ( int n ) { List < int > a = new List < int > ( ) ; int i = 1 ; while ( i <= n ) a . Add ( i ++ ) ; int ways = 0 ; do { bool flag = ( a [ 0 ] == 1 ) ; for ( int j = 1 ; j < n ; j ++ ) { if ( Math . Abs ( a [ j ] - a [ j - 1 ] ) > 2 ) flag = false ; } if ( flag ) ways ++ ; } while ( next_permutation ( a ) ) ; return ways ; } static bool next_permutation ( List < int > p ) { for ( int a = p . Count - 2 ; a >= 0 ; -- a ) if ( p [ a ] < p [ a + 1 ] ) for ( int b = p . Count - 1 ; ; -- b ) if ( p [ b ] > p [ a ] ) { int t = p [ a ] ; p [ a ] = p [ b ] ; p [ b ] = t ; for ( ++ a , b = p . Count - 1 ; a < b ; ++ a , -- b ) { t = p [ a ] ; p [ a ] = p [ b ] ; p [ b ] = t ; } return true ; } return false ; } public static void Main ( String [ ] args ) { int n = 6 ; Console . Write ( countWays ( n ) ) ; } }
Count number of ways to arrange first N numbers | C # implementation of the approach ; Function to return the count of required arrangements ; Create the dp array ; Initialize the base cases as explained above ; ( 12 ) as the only possibility ; Generate answer for greater values ; dp [ n ] contains the desired answer ; Driver code
using System ; class GFG { static int countWays ( int n ) { int [ ] dp = new int [ n + 1 ] ; dp [ 0 ] = 0 ; dp [ 1 ] = 1 ; dp [ 2 ] = 1 ; for ( int i = 3 ; i <= n ; i ++ ) { dp [ i ] = dp [ i - 1 ] + dp [ i - 3 ] + 1 ; } return dp [ n ] ; } public static void Main ( ) { int n = 6 ; Console . WriteLine ( countWays ( n ) ) ; } }
Number of shortest paths to reach every cell from bottom | C # program to find number of shortest paths ; Function to find number of shortest paths ; Compute the grid starting from the bottom - left corner ; Print the grid ; Driver code ; Function call
using System ; class GFG { static void NumberOfShortestPaths ( int n , int m ) { int [ , ] a = new int [ n , m ] ; for ( int i = n - 1 ; i >= 0 ; i -- ) { for ( int j = 0 ; j < m ; j ++ ) { if ( j == 0 i == n - 1 ) a [ i , j ] = 1 ; else a [ i , j ] = a [ i , j - 1 ] + a [ i + 1 , j ] ; } } for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < m ; j ++ ) { Console . Write ( a [ i , j ] + " ▁ " ) ; } Console . Write ( " STRNEWLINE " ) ; } } public static void Main ( String [ ] args ) { int n = 5 , m = 2 ; NumberOfShortestPaths ( n , m ) ; } }
Maximum sum combination from two arrays | C # program to maximum sum combination from two arrays ; Function to maximum sum combination from two arrays ; To store dp value ; For loop to calculate the value of dp ; Return the required answer ; Driver code ; Function call
using System ; class GFG { static int Max_Sum ( int [ ] arr1 , int [ ] arr2 , int n ) { int [ , ] dp = new int [ n , 2 ] ; for ( int i = 0 ; i < n ; i ++ ) { if ( i == 0 ) { dp [ i , 0 ] = arr1 [ i ] ; dp [ i , 1 ] = arr2 [ i ] ; continue ; } dp [ i , 0 ] = Math . Max ( dp [ i - 1 , 0 ] , dp [ i - 1 , 1 ] + arr1 [ i ] ) ; dp [ i , 1 ] = Math . Max ( dp [ i - 1 , 1 ] , dp [ i - 1 , 0 ] + arr2 [ i ] ) ; } return Math . Max ( dp [ n - 1 , 0 ] , dp [ n - 1 , 1 ] ) ; } public static void Main ( ) { int [ ] arr1 = { 9 , 3 , 5 , 7 , 3 } ; int [ ] arr2 = { 5 , 8 , 1 , 4 , 5 } ; int n = arr1 . Length ; Console . WriteLine ( Max_Sum ( arr1 , arr2 , n ) ) ; } }
Partition the array in K segments such that bitwise AND of individual segment sum is maximized | C # program to find maximum possible AND ; Function to check whether a k - segment partition is possible such that bitwise AND is ' mask ' ; dp [ i , j ] stores whether it is possible to partition first i elements into j - segments such that all j - segments are ' good ' ; Initialising dp ; Filling dp in bottom - up manner ; Finding a cut such that first l elements can be partitioned into j - 1 ' good ' segments and arr [ l + 1 ] + ... + arr [ i ] is a ' good ' segment ; Function to find maximum possible AND ; Array to store prefix sums ; Maximum no of bits in the possible answer ; This will store the final answer ; Constructing answer greedily selecting from the higher most bit ; Checking if array can be partitioned such that the bitwise AND is ans | ( 1 << i ) ; if possible , update the answer ; Return the final answer ; Driver code ; n = 11 , first element is zero to make array 1 based indexing . So , number of elements are 10 ; Function call
using System ; class GFG { static Boolean checkpossible ( int mask , int [ ] arr , int [ ] prefix , int n , int k ) { int i , j ; Boolean [ , ] dp = new Boolean [ n + 1 , k + 1 ] ; for ( i = 0 ; i < n + 1 ; i ++ ) { for ( j = 0 ; j < k + 1 ; j ++ ) { dp [ i , j ] = false ; } } dp [ 0 , 0 ] = true ; for ( i = 1 ; i <= n ; i ++ ) { for ( j = 1 ; j <= k ; j ++ ) { for ( int l = i - 1 ; l >= 0 ; -- l ) { if ( dp [ l , j - 1 ] && ( ( ( prefix [ i ] - prefix [ l ] ) & mask ) == mask ) ) { dp [ i , j ] = true ; break ; } } } } return dp [ n , k ] ; } static int Partition ( int [ ] arr , int n , int k ) { int [ ] prefix = new int [ n + 1 ] ; for ( int i = 1 ; i <= n ; i ++ ) { prefix [ i ] = prefix [ i - 1 ] + arr [ i ] ; } int LOGS = 20 ; int ans = 0 ; for ( int i = LOGS ; i >= 0 ; -- i ) { if ( checkpossible ( ans | ( 1 << i ) , arr , prefix , n , k ) ) { ans = ans | ( 1 << i ) ; } } return ans ; } public static void Main ( String [ ] args ) { int [ ] arr = { 0 , 1 , 2 , 7 , 10 , 23 , 21 , 6 , 8 , 7 , 3 } ; int k = 2 ; int n = arr . Length - 1 ; Console . WriteLine ( Partition ( arr , n , k ) ) ; } }
Cost Based Tower of Hanoi | C # implementation of the approach ; Function to initialize the dp table ; Initialize with maximum value ; Function to return the minimum cost ; Base case ; If problem is already solved , return the pre - calculated answer ; Number of the auxiliary disk ; Initialize the minimum cost as Infinity ; Calculationg the cost for first case ; Calculating the cost for second case ; Minimum of both the above cases ; Store it in the dp table ; Return the minimum cost ; Driver code
using System ; class GFG { static int RODS = 3 ; static int N = 3 ; static int [ , , ] dp = new int [ N + 1 , RODS + 1 , RODS + 1 ] ; static void initialize ( ) { for ( int i = 0 ; i <= N ; i += 1 ) { for ( int j = 1 ; j <= RODS ; j ++ ) { for ( int k = 1 ; k <= RODS ; k += 1 ) { dp [ i , j , k ] = int . MaxValue ; } } } } static int mincost ( int idx , int src , int dest , int [ , ] costs ) { if ( idx > N ) return 0 ; if ( dp [ idx , src , dest ] != int . MaxValue ) return dp [ idx , src , dest ] ; int rem = 6 - ( src + dest ) ; int ans = int . MaxValue ; int case1 = costs [ src - 1 , dest - 1 ] + mincost ( idx + 1 , src , rem , costs ) + mincost ( idx + 1 , rem , dest , costs ) ; int case2 = costs [ src - 1 , rem - 1 ] + mincost ( idx + 1 , src , dest , costs ) + mincost ( idx + 1 , dest , src , costs ) + costs [ rem - 1 , dest - 1 ] + mincost ( idx + 1 , src , dest , costs ) ; ans = Math . Min ( case1 , case2 ) ; dp [ idx , src , dest ] = ans ; return ans ; } public static void Main ( String [ ] args ) { int [ , ] costs = { { 0 , 1 , 2 } , { 2 , 0 , 1 } , { 3 , 2 , 0 } } ; initialize ( ) ; Console . WriteLine ( mincost ( 1 , 1 , 3 , costs ) ) ; } }
Minimum time required to rot all oranges | Dynamic Programming | C # implementation of the above approach ; DP table to memoize the values ; Visited array to keep track of visited nodes in order to avoid infinite loops ; Function to return the minimum of four numbers ; Function to return the minimum distance to any rotten orange from [ i , j ] ; If i , j lie outside the array ; If 0 then it can 't lead to any path so return INT_MAX ; If 2 then we have reached our rotten oranges so return from here ; If this node is already visited then return to avoid infinite loops ; Mark the current node as visited ; Check in all four possible directions ; Take the minimum of all ; If result already exists in the table check if min_value is less than existing value ; Function to return the minimum time required to rot all the oranges ; Calculate the minimum distances to any rotten orange from all the fresh oranges ; Pick the maximum distance of fresh orange to some rotten orange ; If all oranges can be rotten ; Driver Code
using System ; class GFG { static int C = 5 ; static int R = 3 ; static int INT_MAX = 10000000 ; static int [ , ] table = new int [ R , C ] ; static int [ , ] visited = new int [ R , C ] ; static int min ( int p , int q , int r , int s ) { int temp1 = p < q ? p : q ; int temp2 = r < s ? r : s ; if ( temp1 < temp2 ) return temp1 ; return temp2 ; } static int Distance ( int [ , ] arr , int i , int j ) { if ( i >= R j >= C i < 0 j < 0 ) return INT_MAX ; else if ( arr [ i , j ] == 0 ) { table [ i , j ] = INT_MAX ; return INT_MAX ; } else if ( arr [ i , j ] == 2 ) { table [ i , j ] = 0 ; return 0 ; } else if ( visited [ i , j ] == 1 ) { return INT_MAX ; } else { visited [ i , j ] = 1 ; int temp1 = Distance ( arr , i + 1 , j ) ; int temp2 = Distance ( arr , i - 1 , j ) ; int temp3 = Distance ( arr , i , j + 1 ) ; int temp4 = Distance ( arr , i , j - 1 ) ; int min_value = 1 + min ( temp1 , temp2 , temp3 , temp4 ) ; if ( table [ i , j ] > 0 && table [ i , j ] < INT_MAX ) { if ( min_value < table [ i , j ] ) table [ i , j ] = min_value ; } else table [ i , j ] = min_value ; visited [ i , j ] = 0 ; } return table [ i , j ] ; } static int minTime ( int [ , ] arr ) { int max = 0 ; for ( int i = 0 ; i < R ; i ++ ) { for ( int j = 0 ; j < C ; j ++ ) { if ( arr [ i , j ] == 1 ) Distance ( arr , i , j ) ; } } for ( int i = 0 ; i < R ; i ++ ) { for ( int j = 0 ; j < C ; j ++ ) { if ( arr [ i , j ] == 1 && table [ i , j ] > max ) max = table [ i , j ] ; } } if ( max < INT_MAX ) return max ; return - 1 ; } public static void Main ( string [ ] args ) { int [ , ] arr = { { 2 , 1 , 0 , 2 , 1 } , { 0 , 0 , 1 , 2 , 1 } , { 1 , 0 , 0 , 2 , 1 } } ; Console . Write ( minTime ( arr ) ) ; } }
Maximum sum of non | C # program to implement above approach ; Variable to store states of dp ; Variable to check if a given state has been solved ; Function to find the maximum sum subsequence such that no two elements are adjacent ; Base case ; To check if a state has been solved ; Variable to store prefix sum for sub - array { i , j } ; Required recurrence relation ; Returning the value ; Driver code ; Input array
using System ; class GFG { static int maxLen = 10 ; static int [ ] dp = new int [ maxLen ] ; static bool [ ] visit = new bool [ maxLen ] ; static int maxSum ( int [ ] arr , int i , int n , int k ) { if ( i >= n ) return 0 ; if ( visit [ i ] ) return dp [ i ] ; visit [ i ] = true ; int tot = 0 ; dp [ i ] = maxSum ( arr , i + 1 , n , k ) ; for ( int j = i ; j < ( i + k ) && ( j < n ) ; j ++ ) { tot += arr [ j ] ; dp [ i ] = Math . Max ( dp [ i ] , tot + maxSum ( arr , j + 2 , n , k ) ) ; } return dp [ i ] ; } static public void Main ( ) { int [ ] arr = { - 1 , 2 , - 3 , 4 , 5 } ; int k = 2 ; int n = arr . Length ; Console . WriteLine ( maxSum ( arr , 0 , n , k ) ) ; } }
Maximum subset sum such that no two elements in set have same digit in them | C # implementation of above approach ; Function to create mask for every number ; Recursion for Filling DP array ; Base Condition ; Recurrence Relation ; Function to find Maximum Subset Sum ; Initialize DP array ; Iterate over all possible masks of 10 bit number ; Driver Code
using System ; class GFG { static int [ ] dp = new int [ 1024 ] ; static int get_binary ( int u ) { int ans = 0 ; while ( u > 0 ) { int rem = u % 10 ; ans |= ( 1 << rem ) ; u /= 10 ; } return ans ; } static int recur ( int u , int [ ] array , int n ) { if ( u == 0 ) return 0 ; if ( dp [ u ] != - 1 ) return dp [ u ] ; for ( int i = 0 ; i < n ; i ++ ) { int mask = get_binary ( array [ i ] ) ; if ( ( mask u ) == u ) { dp [ u ] = Math . Max ( Math . Max ( 0 , dp [ u ^ mask ] ) + array [ i ] , dp [ u ] ) ; } } return dp [ u ] ; } static int solve ( int [ ] array , int n ) { for ( int i = 0 ; i < ( 1 << 10 ) ; i ++ ) { dp [ i ] = - 1 ; } int ans = 0 ; for ( int i = 0 ; i < ( 1 << 10 ) ; i ++ ) { ans = Math . Max ( ans , recur ( i , array , n ) ) ; } return ans ; } static public void Main ( ) { int [ ] array = { 22 , 132 , 4 , 45 , 12 , 223 } ; int n = array . Length ; Console . WriteLine ( solve ( array , n ) ) ; } }
Minimize the sum after choosing elements from the given three arrays | C # implementation of the above approach ; Function to return the minimized sum ; If all the indices have been used ; If this value is pre - calculated then return its value from dp array instead of re - computing it ; If A [ i - 1 ] was chosen previously then only B [ i ] or C [ i ] can chosen now choose the one which leads to the minimum sum ; If B [ i - 1 ] was chosen previously then only A [ i ] or C [ i ] can chosen now choose the one which leads to the minimum sum ; If C [ i - 1 ] was chosen previously then only A [ i ] or B [ i ] can chosen now choose the one which leads to the minimum sum ; Driver code ; Initialize the dp [ ] [ ] array ; min ( start with A [ 0 ] , start with B [ 0 ] , start with C [ 0 ] )
using System ; class GFG { static int SIZE = 3 ; static int N = 3 ; static int minSum ( int [ ] A , int [ ] B , int [ ] C , int i , int n , int curr , int [ , ] dp ) { if ( n <= 0 ) return 0 ; if ( dp [ n , curr ] != - 1 ) return dp [ n , curr ] ; if ( curr == 0 ) { return dp [ n , curr ] = Math . Min ( B [ i ] + minSum ( A , B , C , i + 1 , n - 1 , 1 , dp ) , C [ i ] + minSum ( A , B , C , i + 1 , n - 1 , 2 , dp ) ) ; } if ( curr == 1 ) return dp [ n , curr ] = Math . Min ( A [ i ] + minSum ( A , B , C , i + 1 , n - 1 , 0 , dp ) , C [ i ] + minSum ( A , B , C , i + 1 , n - 1 , 2 , dp ) ) ; return dp [ n , curr ] = Math . Min ( A [ i ] + minSum ( A , B , C , i + 1 , n - 1 , 0 , dp ) , B [ i ] + minSum ( A , B , C , i + 1 , n - 1 , 1 , dp ) ) ; } public static void Main ( ) { int [ ] A = { 1 , 50 , 1 } ; int [ ] B = { 50 , 50 , 50 } ; int [ ] C = { 50 , 50 , 50 } ; int [ , ] dp = new int [ SIZE , N ] ; for ( int i = 0 ; i < SIZE ; i ++ ) for ( int j = 0 ; j < N ; j ++ ) dp [ i , j ] = - 1 ; Console . WriteLine ( Math . Min ( A [ 0 ] + minSum ( A , B , C , 1 , SIZE - 1 , 0 , dp ) , Math . Min ( B [ 0 ] + minSum ( A , B , C , 1 , SIZE - 1 , 1 , dp ) , C [ 0 ] + minSum ( A , B , C , 1 , SIZE - 1 , 2 , dp ) ) ) ) ; } }
Maximise matrix sum by following the given Path | C # implementation of the approach ; To store the states of the DP ; Function to return the maximum of the three integers ; Function to return the maximum score ; Base cases ; If the state has already been solved then return it ; Marking the state as solved ; Growing phase ; } Shrinking phase ; Returning the solved state ; Driver code
using System ; class GFG { static int n = 3 ; static int [ , , ] dp = new int [ n , n , 2 ] ; static bool [ , , ] v = new bool [ n , n , 2 ] ; static int max ( int a , int b , int c ) { int m = a ; if ( m < b ) { m = b ; } if ( m < c ) { m = c ; } return m ; } static int maxScore ( int [ , ] arr , int i , int j , int s ) { if ( i > n - 1 i < 0 j > n - 1 ) { return 0 ; } if ( ( i == 0 ) && ( j == ( n - 1 ) ) ) { return arr [ i , j ] ; } if ( v [ i , j , s ] ) { return dp [ i , j , s ] ; } v [ i , j , s ] = true ; if ( s != 1 ) { dp [ i , j , s ] = arr [ i , j ] + Math . Max ( maxScore ( arr , i + 1 , j , s ) , Math . Max ( maxScore ( arr , i , j + 1 , s ) , maxScore ( arr , i - 1 , j , ( s == 1 ) ? 0 : 1 ) ) ) ; else { dp [ i , j , s ] = arr [ i , j ] + Math . Max ( maxScore ( arr , i - 1 , j , s ) , maxScore ( arr , i , j + 1 , s ) ) ; } return dp [ i , j , s ] ; } static public void Main ( ) { int [ , ] arr = { { 1 , 1 , 1 } , { 1 , 5 , 1 } , { 1 , 1 , 1 } } ; Console . WriteLine ( maxScore ( arr , 0 , 0 , 0 ) ) ; } }
Find maximum topics to prepare in order to pass the exam | C # implementation of the approach ; Function to return the maximum marks by considering topics which can be completed in the given time duration ; If we are given 0 time then nothing can be done So all values are 0 ; If we are given 0 topics then the time required will be 0 for sure ; Calculating the maximum marks that can be achieved under the given time constraints ; If time taken to read that topic is more than the time left now at position j then do no read that topic ; Two cases arise : 1 ) Considering current topic 2 ) Ignoring current topic We are finding maximum of ( current topic weightage + topics which can be done in leftover time - current topic time ) and ignoring current topic weightage sum ; Moving upwards in table from bottom right to calculate the total time taken to read the topics which can be done in given time and have highest weightage sum ; It means we have not considered reading this topic for max weightage sum ; Adding the topic time ; Evaluating the left over time after considering this current topic ; One topic completed ; It contains the maximum weightage sum formed by considering the topics ; Condition when exam cannot be passed ; Return the marks that can be obtained after passing the exam ; Driver code ; Number of topics , hours left and the passing marks ; n + 1 is taken for simplicity in loops Array will be indexed starting from 1
using System ; class GFG { static int MaximumMarks ( int [ ] marksarr , int [ ] timearr , int h , int n , int p ) { int no_of_topics = n + 1 ; int total_time = h + 1 ; int [ , ] T = new int [ no_of_topics , total_time ] ; int i , j ; for ( i = 0 ; i < no_of_topics ; i ++ ) { T [ i , 0 ] = 0 ; } for ( j = 0 ; j < total_time ; j ++ ) { T [ 0 , j ] = 0 ; } for ( i = 1 ; i < no_of_topics ; i ++ ) { for ( j = 1 ; j < total_time ; j ++ ) { if ( j < timearr [ i ] ) { T [ i , j ] = T [ i - 1 , j ] ; } else { T [ i , j ] = Math . Max ( marksarr [ i ] + T [ i - 1 , j - timearr [ i ] ] , T [ i - 1 , j ] ) ; } } } i = no_of_topics - 1 ; j = total_time - 1 ; int sum = 0 ; while ( i > 0 && j > 0 ) { if ( T [ i , j ] == T [ i - 1 , j ] ) { i -- ; } else { sum += timearr [ i ] ; j -= timearr [ i ] ; i -- ; } } int marks = T [ no_of_topics - 1 , total_time - 1 ] ; if ( marks < p ) return - 1 ; return sum ; } public static void Main ( String [ ] args ) { int n = 4 , h = 10 , p = 10 ; int [ ] marksarr = { 0 , 6 , 4 , 2 , 8 } ; int [ ] timearr = { 0 , 4 , 6 , 2 , 7 } ; Console . WriteLine ( MaximumMarks ( marksarr , timearr , h , n , p ) ) ; } }
Minimize the number of steps required to reach the end of the array | C # implementation of the above approach ; variable to store states of dp ; variable to check if a given state has been solved ; Function to find the minimum number of steps required to reach the end of the array ; base case ; to check if a state has been solved ; required recurrence relation ; returning the value ; Driver code
using System ; class GFG { static int maxLen = 10 ; static int maskLen = 130 ; static int [ , ] dp = new int [ maxLen , maskLen ] ; static bool [ , ] v = new bool [ maxLen , maskLen ] ; static int minSteps ( int [ ] arr , int i , int mask , int n ) { if ( i == n - 1 ) { return 0 ; } if ( i > n - 1 i < 0 ) { return 9999999 ; } if ( ( mask >> i ) % 2 == 1 ) { return 9999999 ; } if ( v [ i , mask ] ) { return dp [ i , mask ] ; } v [ i , mask ] = true ; dp [ i , mask ] = 1 + Math . Min ( minSteps ( arr , i - arr [ i ] , ( mask | ( 1 << i ) ) , n ) , minSteps ( arr , i + arr [ i ] , ( mask | ( 1 << i ) ) , n ) ) ; return dp [ i , mask ] ; } static public void Main ( ) { int [ ] arr = { 1 , 2 , 2 , 2 , 1 , 1 } ; int n = arr . Length ; int ans = minSteps ( arr , 0 , 0 , n ) ; if ( ans >= 9999999 ) { Console . WriteLine ( - 1 ) ; } else { Console . WriteLine ( ans ) ; } } }
Optimal Strategy for a Game | Set 2 | C # program to find out maximum value from a given sequence of coins ; For both of your choices , the opponent gives you total sum minus maximum of his value ; Returns optimal value possible that a player can collect from an array of coins of size n . Note than n must be even ; Driver code
using System ; class GFG { static int oSRec ( int [ ] arr , int i , int j , int sum ) { if ( j == i + 1 ) return Math . Max ( arr [ i ] , arr [ j ] ) ; return Math . Max ( ( sum - oSRec ( arr , i + 1 , j , sum - arr [ i ] ) ) , ( sum - oSRec ( arr , i , j - 1 , sum - arr [ j ] ) ) ) ; } static int optimalStrategyOfGame ( int [ ] arr , int n ) { int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) { sum += arr [ i ] ; } return oSRec ( arr , 0 , n - 1 , sum ) ; } static public void Main ( ) { int [ ] arr1 = { 8 , 15 , 3 , 7 } ; int n = arr1 . Length ; Console . WriteLine ( optimalStrategyOfGame ( arr1 , n ) ) ; int [ ] arr2 = { 2 , 2 , 2 , 2 } ; n = arr2 . Length ; Console . WriteLine ( optimalStrategyOfGame ( arr2 , n ) ) ; int [ ] arr3 = { 20 , 30 , 2 , 2 , 2 , 10 } ; n = arr3 . Length ; Console . WriteLine ( optimalStrategyOfGame ( arr3 , n ) ) ; } }
Minimum number of sub | C # implementation of the approach ; Function that returns true if n is a power of 5 ; Function to return the decimal value of binary equivalent ; Function to return the minimum cuts required ; Alongocating memory for dp [ ] array ; From length 1 to n ; If previous character is '0' then ignore to avoid number with leading 0 s . ; Ignore s [ j ] = '0' starting numbers ; Number formed from s [ j ... . i ] ; Check for power of 5 ; Assigning min value to get min cut possible ; ( n + 1 ) to check if all the Strings are traversed and no divisible by 5 is obtained like 000000 ; Driver code
using System ; class GFG { static Boolean ispower ( long n ) { if ( n < 125 ) { return ( n == 1 n == 5 n == 25 ) ; } if ( n % 125 != 0 ) { return false ; } else { return ispower ( n / 125 ) ; } } static long number ( String s , int i , int j ) { long ans = 0 ; for ( int x = i ; x < j ; x ++ ) { ans = ans * 2 + ( s [ x ] - '0' ) ; } return ans ; } static int minCuts ( String s , int n ) { int [ ] dp = new int [ n + 1 ] ; for ( int i = 0 ; i <= n ; i ++ ) dp [ i ] = n + 1 ; dp [ 0 ] = 0 ; for ( int i = 1 ; i <= n ; i ++ ) { if ( s [ i - 1 ] == '0' ) { continue ; } for ( int j = 0 ; j < i ; j ++ ) { if ( s [ j ] == '0' ) { continue ; } long num = number ( s , j , i ) ; if ( ! ispower ( num ) ) { continue ; } dp [ i ] = Math . Min ( dp [ i ] , dp [ j ] + 1 ) ; } } return ( ( dp [ n ] < n + 1 ) ? dp [ n ] : - 1 ) ; } public static void Main ( String [ ] args ) { String s = "101101101" ; int n = s . Length ; Console . WriteLine ( minCuts ( s , n ) ) ; } }
Minimum number of cubes whose sum equals to given number N | C # implementation of the approach ; Function to return the minimum number of cubes whose sum is k ; If k is less than the 2 ^ 3 ; Initialize with the maximum number of cubes required ; Driver code
using System ; class GFG { static int MinOfCubed ( int k ) { if ( k < 8 ) return k ; int res = k ; for ( int i = 1 ; i <= k ; i ++ ) { if ( ( i * i * i ) > k ) return res ; res = Math . Min ( res , MinOfCubed ( k - ( i * i * i ) ) + 1 ) ; } return res ; } static public void Main ( ) { int num = 15 ; Console . WriteLine ( MinOfCubed ( num ) ) ; } }
Minimum number of cubes whose sum equals to given number N | C # implementation of the approach ; Function to return the minimum number of cubes whose sum is k ; While current perfect cube is less than current element ; If i is a perfect cube ; i = ( i - 1 ) + 1 ^ 3 ; Next perfect cube ; Re - initialization for next element ; Driver code
using System ; class GFG { static int MinOfCubedDP ( int k ) { int [ ] DP = new int [ k + 1 ] ; int j = 1 , t = 1 ; DP [ 0 ] = 0 ; for ( int i = 1 ; i <= k ; i ++ ) { DP [ i ] = int . MaxValue ; while ( j <= i ) { if ( j == i ) DP [ i ] = 1 ; else if ( DP [ i ] > DP [ i - j ] ) DP [ i ] = DP [ i - j ] + 1 ; t ++ ; j = t * t * t ; } t = j = 1 ; } return DP [ k ] ; } public static void Main ( ) { int num = 15 ; Console . WriteLine ( MinOfCubedDP ( num ) ) ; } }
Maximum Subarray Sum after inverting at most two elements | C # implementation of the approach ; Function to return the maximum required sub - array sum ; Creating one based indexing ; 2d array to contain solution for each step ; Case 1 : Choosing current or ( current + previous ) whichever is smaller ; Case 2 : ( a ) Altering sign and add to previous case 1 or value 0 ; Case 2 : ( b ) Adding current element with previous case 2 and updating the maximum ; Case 3 : ( a ) Altering sign and add to previous case 2 ; Case 3 : ( b ) Adding current element with previous case 3 ; Updating the maximum value of variable ans ; Return the final solution ; Driver code
using System ; class GFG { static int maxSum ( int [ ] a , int n ) { int ans = 0 ; int [ ] arr = new int [ n + 1 ] ; for ( int i = 1 ; i <= n ; i ++ ) arr [ i ] = a [ i - 1 ] ; int [ , ] dp = new int [ n + 1 , 3 ] ; for ( int i = 1 ; i <= n ; ++ i ) { dp [ i , 0 ] = Math . Max ( arr [ i ] , dp [ i - 1 , 0 ] + arr [ i ] ) ; dp [ i , 1 ] = Math . Max ( 0 , dp [ i - 1 , 0 ] ) - arr [ i ] ; if ( i >= 2 ) dp [ i , 1 ] = Math . Max ( dp [ i , 1 ] , dp [ i - 1 , 1 ] + arr [ i ] ) ; if ( i >= 2 ) dp [ i , 2 ] = dp [ i - 1 , 1 ] - arr [ i ] ; if ( i >= 3 ) dp [ i , 2 ] = Math . Max ( dp [ i , 2 ] , dp [ i - 1 , 2 ] + arr [ i ] ) ; ans = Math . Max ( ans , dp [ i , 0 ] ) ; ans = Math . Max ( ans , dp [ i , 1 ] ) ; ans = Math . Max ( ans , dp [ i , 2 ] ) ; } return ans ; } public static void Main ( ) { int [ ] arr = { - 5 , 3 , 2 , 7 , - 8 , 3 , 7 , - 9 , 10 , 12 , - 6 } ; int n = arr . Length ; Console . WriteLine ( maxSum ( arr , n ) ) ; } }
Maximum sum possible for a sub | C # implementation of the approach ; Function to return the maximum sum possible ; dp [ i ] represent the maximum sum so far after reaching current position i ; Initialize dp [ 0 ] ; Initialize the dp values till k since any two elements included in the sub - sequence must be atleast k indices apart , and thus first element and second element will be k indices apart ; Fill remaining positions ; Return the maximum sum ; Driver code
using System ; using System . Linq ; class GFG { static int maxSum ( int [ ] arr , int k , int n ) { if ( n == 0 ) return 0 ; if ( n == 1 ) return arr [ 0 ] ; if ( n == 2 ) return Math . Max ( arr [ 0 ] , arr [ 1 ] ) ; int [ ] dp = new int [ n ] ; dp [ 0 ] = arr [ 0 ] ; for ( int i = 1 ; i <= k ; i ++ ) dp [ i ] = Math . Max ( arr [ i ] , dp [ i - 1 ] ) ; for ( int i = k + 1 ; i < n ; i ++ ) dp [ i ] = Math . Max ( arr [ i ] , dp [ i - ( k + 1 ) ] + arr [ i ] ) ; int max = dp . Max ( ) ; return max ; } static void Main ( ) { int [ ] arr = { 6 , 7 , 1 , 3 , 8 , 2 , 4 } ; int n = arr . Length ; int k = 2 ; Console . WriteLine ( maxSum ( arr , k , n ) ) ; } }
Minimum cost to form a number X by adding up powers of 2 | C # implementation of the approach ; Function to return the minimum cost ; Re - compute the array ; Add answers for set bits ; If bit is set ; Increase the counter ; Right shift the number ; Driver code
using System ; class GFG { public static int MinimumCost ( int [ ] a , int n , int x ) { for ( int i = 1 ; i < n ; i ++ ) { a [ i ] = Math . Min ( a [ i ] , 2 * a [ i - 1 ] ) ; } int ind = 0 ; int sum = 0 ; while ( x > 0 ) { if ( x != 0 ) sum += a [ ind ] ; ind ++ ; x = x >> 1 ; } return sum ; } public static void Main ( ) { int [ ] a = { 20 , 50 , 60 , 90 } ; int x = 7 ; int n = a . Length ; Console . WriteLine ( MinimumCost ( a , n , x ) ) ; } }
Ways to form an array having integers in given range such that total sum is divisible by 2 | C # implementation of the approach ; Function to return the number of ways to form an array of size n such that sum of all elements is divisible by 2 ; Represents first and last numbers of each type ( modulo 0 and 1 ) ; Count of numbers of each type between range ; Base Cases ; Ways to form array whose sum upto i numbers modulo 2 is 0 ; Ways to form array whose sum upto i numbers modulo 2 is 1 ; Return the required count of ways ; Driver Code
using System ; class GFG { static int countWays ( int n , int l , int r ) { int tL = l , tR = r ; int [ ] L = new int [ 3 ] ; int [ ] R = new int [ 3 ] ; L [ l % 2 ] = l ; R [ r % 2 ] = r ; l ++ ; r -- ; if ( l <= tR && r >= tL ) { L [ l % 2 ] = l ; R [ r % 2 ] = r ; } int cnt0 = 0 , cnt1 = 0 ; if ( R [ 0 ] > 0 && L [ 0 ] > 0 ) cnt0 = ( R [ 0 ] - L [ 0 ] ) / 2 + 1 ; if ( R [ 1 ] > 0 && L [ 1 ] > 0 ) cnt1 = ( R [ 1 ] - L [ 1 ] ) / 2 + 1 ; int [ , ] dp = new int [ n + 1 , 3 ] ; dp [ 1 , 0 ] = cnt0 ; dp [ 1 , 1 ] = cnt1 ; for ( int i = 2 ; i <= n ; i ++ ) { dp [ i , 0 ] = ( cnt0 * dp [ i - 1 , 0 ] + cnt1 * dp [ i - 1 , 1 ] ) ; dp [ i , 1 ] = ( cnt0 * dp [ i - 1 , 1 ] + cnt1 * dp [ i - 1 , 0 ] ) ; } return dp [ n , 0 ] ; } static void Main ( ) { int n = 2 , l = 1 , r = 3 ; Console . WriteLine ( countWays ( n , l , r ) ) ; } }
Color N boxes using M colors such that K boxes have different color from the box on its left | C # Program to Paint N boxes using M colors such that K boxes have color different from color of box on its left ; This function returns the required number of ways where idx is the current index and diff is number of boxes having different color from box on its left ; Base Case ; If already computed ; Either paint with same color as previous one ; Or paint with remaining ( M - 1 ) colors ; Driver code ; Multiply M since first box can be painted with any of the M colors and start solving from 2 nd box
using System ; class GFG { static int M = 1001 ; static int MOD = 998244353 ; static int [ , ] dp = new int [ M , M ] ; static int solve ( int idx , int diff , int N , int M , int K ) { if ( idx > N ) { if ( diff == K ) return 1 ; return 0 ; } if ( dp [ idx , diff ] != - 1 ) return dp [ idx , diff ] ; int ans = solve ( idx + 1 , diff , N , M , K ) ; ans += ( M - 1 ) * solve ( idx + 1 , diff + 1 , N , M , K ) ; return dp [ idx , diff ] = ans % MOD ; } public static void Main ( ) { int N = 3 , M = 3 , K = 0 ; for ( int i = 0 ; i <= M ; i ++ ) for ( int j = 0 ; j <= M ; j ++ ) dp [ i , j ] = - 1 ; Console . WriteLine ( ( M * solve ( 2 , 0 , N , M , K ) ) ) ; } }
Maximum path sum in an Inverted triangle | SET 2 | C # program implementation of Max sum problem in a triangle ; Function for finding maximum sum ; Loop for bottom - up calculation ; For each element , check both elements just below the number and below left to the number add the maximum of them to it ; Return the maximum sum ; Driver Code
using System ; class GFG { static int N = 3 ; static int maxPathSum ( int [ , ] tri ) { int ans = 0 ; for ( int i = N - 2 ; i >= 0 ; i -- ) { for ( int j = 0 ; j < N - i ; j ++ ) { if ( j - 1 >= 0 ) tri [ i , j ] += Math . Max ( tri [ i + 1 , j ] , tri [ i + 1 , j - 1 ] ) ; else tri [ i , j ] += tri [ i + 1 , j ] ; ans = Math . Max ( ans , tri [ i , j ] ) ; } } return ans ; } public static void Main ( ) { int [ , ] tri = { { 1 , 5 , 3 } , { 4 , 8 , 0 } , { 1 , 0 , 0 } } ; Console . WriteLine ( maxPathSum ( tri ) ) ; } }
Count no . of ordered subsets having a particular XOR value | C # implementation of the approach ; Returns count of ordered subsets of arr [ ] with XOR value = K ; Find maximum element in arr [ ] ; Maximum possible XOR value ; The value of dp [ i ] [ j ] [ k ] is the number of subsets of length k having XOR of their elements as j from the set arr [ 0. . . i - 1 ] ; Initializing all the values of dp [ i ] [ j ] [ k ] as 0 ; The xor of empty subset is 0 ; Fill the dp table ; The answer is the number of subsets of all lengths from set arr [ 0. . n - 1 ] having XOR of elements as k ; Driver code
using System ; class GFG { static int subsetXOR ( int [ ] arr , int n , int K ) { int max_ele = arr [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) if ( arr [ i ] > max_ele ) max_ele = arr [ i ] ; int m = ( 1 << ( int ) ( Math . Log ( max_ele ) / Math . Log ( 2 ) + 1 ) ) - 1 ; int [ , , ] dp = new int [ n + 1 , m + 1 , n + 1 ] ; for ( int i = 0 ; i <= n ; i ++ ) for ( int j = 0 ; j <= m ; j ++ ) for ( int k = 0 ; k <= n ; k ++ ) dp [ i , j , k ] = 0 ; for ( int i = 0 ; i <= n ; i ++ ) dp [ i , 0 , 0 ] = 1 ; for ( int i = 1 ; i <= n ; i ++ ) { for ( int j = 0 ; j <= m ; j ++ ) { for ( int k = 0 ; k <= n ; k ++ ) { dp [ i , j , k ] = dp [ i - 1 , j , k ] ; if ( k != 0 ) { dp [ i , j , k ] += k * dp [ i - 1 , j ^ arr [ i - 1 ] , k - 1 ] ; } } } } int ans = 0 ; for ( int i = 1 ; i <= n ; i ++ ) { ans += dp [ n , K , i ] ; } return ans ; } public static void Main ( ) { int [ ] arr = { 1 , 2 , 3 } ; int k = 1 ; int n = arr . Length ; Console . WriteLine ( subsetXOR ( arr , n , k ) ) ; } }
Possible cuts of a number such that maximum parts are divisible by 3 | C # program to find the maximum number of numbers divisible by 3 in large number ; This will contain the count of the splits ; This will keep sum of all successive integers , when they are indivisible by 3 ; This is the condition of finding a split ; Driver code
using System ; class GFG { static int get_max_splits ( String num_String ) { int count = 0 , current_num ; int running_sum = 0 ; for ( int i = 0 ; i < num_String . Length ; i ++ ) { current_num = num_String [ i ] - '0' ; running_sum += current_num ; if ( current_num % 3 == 0 || ( running_sum != 0 && running_sum % 3 == 0 ) ) { count += 1 ; running_sum = 0 ; } } return count ; } public static void Main ( String [ ] args ) { Console . Write ( get_max_splits ( "12345" ) + " STRNEWLINE " ) ; } }
Count of Numbers in a Range where digit d occurs exactly K times | C # Program to find the count of numbers in a range where digit d occurs exactly K times ; states - position , count , tight , nonz ; d is required digit and K is occurrence ; This function returns the count of required numbers from 0 to num ; Last position ; If this result is already computed simply return it ; Maximum limit upto which we can place digit . If tight is 1 , means number has already become smaller so we can place any digit , otherwise num [ pos ] ; Nonz is true if we placed a non zero digit at the starting of the number ; At this position , number becomes smaller ; Next recursive call , also set nonz to 1 if current digit is non zero ; Function to convert x into its digit vector and uses count ( ) function to return the required count ; Initialize dp ; Driver Code
using System ; using System . Collections . Generic ; class GFG { static readonly int M = 20 ; static int [ , , , ] dp = new int [ M , M , 2 , 2 ] ; static int d , K ; static int count ( int pos , int cnt , int tight , int nonz , List < int > num ) { if ( pos == num . Count ) { if ( cnt == K ) return 1 ; return 0 ; } if ( dp [ pos , cnt , tight , nonz ] != - 1 ) return dp [ pos , cnt , tight , nonz ] ; int ans = 0 ; int limit = ( ( tight != 0 ) ? 9 : num [ pos ] ) ; for ( int dig = 0 ; dig <= limit ; dig ++ ) { int currCnt = cnt ; if ( dig == d ) { if ( d != 0 || ( d == 0 && nonz != 0 ) ) currCnt ++ ; } int currTight = tight ; if ( dig < num [ pos ] ) currTight = 1 ; ans += count ( pos + 1 , currCnt , currTight , ( dig != 0 ? 1 : 0 ) , num ) ; } return dp [ pos , cnt , tight , nonz ] = ans ; } static int solve ( int x ) { List < int > num = new List < int > ( ) ; while ( x != 0 ) { num . Add ( x % 10 ) ; x /= 10 ; } num . Reverse ( ) ; for ( int i = 0 ; i < M ; i ++ ) for ( int j = 0 ; j < M ; j ++ ) for ( int k = 0 ; k < 2 ; k ++ ) for ( int l = 0 ; l < 2 ; l ++ ) dp [ i , j , k , l ] = - 1 ; return count ( 0 , 0 , 0 , 0 , num ) ; } public static void Main ( ) { int L = 11 , R = 100 ; d = 2 ; K = 1 ; Console . Write ( solve ( R ) - solve ( L - 1 ) ) ; } }
Count of Numbers in Range where first digit is equal to last digit of the number | C # program to implement the above approach ; Base Case ; Calculating the last digit ; Calculating the first digit ; Driver code
using System ; class GFG { public static int solve ( int x ) { int ans = 0 , first = 0 , last , temp = x ; if ( x < 10 ) return x ; last = x % 10 ; while ( x != 0 ) { first = x % 10 ; x /= 10 ; } if ( first <= last ) ans = 9 + temp / 10 ; else ans = 8 + temp / 10 ; return ans ; } public static void Main ( String [ ] args ) { int L = 2 , R = 60 ; Console . WriteLine ( solve ( R ) - solve ( L - 1 ) ) ; L = 1 ; R = 1000 ; Console . WriteLine ( solve ( R ) - solve ( L - 1 ) ) ; } }
Form N | C # code to find minimum cost to form a N - copy string ; Returns the minimum cost to form a n - copy string Here , x -> Cost to add / remove a single character ' G ' and y -> cost to append the string to itself ; Base Case : to form a 1 - copy string we need to perform an operation of type 1 ( i . e Add ) ; Case1 . Perform a Add operation on ( i - 1 ) - copy string , Case2 . Perform a type 2 operation on ( ( i + 1 ) / 2 ) - copy string ; Case1 . Perform a Add operation on ( i - 1 ) - copy string , Case2 . Perform a type 3 operation on ( i / 2 ) - copy string ; Driver Code
using System ; class GFG { static int findMinimumCost ( int n , int x , int y ) { int [ ] dp = new int [ n + 1 ] ; dp [ 1 ] = x ; for ( int i = 2 ; i <= n ; i ++ ) { if ( ( i & 1 ) != 0 ) { dp [ i ] = Math . Min ( dp [ i - 1 ] + x , dp [ ( i + 1 ) / 2 ] + y + x ) ; } else { dp [ i ] = Math . Min ( dp [ i - 1 ] + x , dp [ i / 2 ] + y ) ; } } return dp [ n ] ; } public static void Main ( ) { int n = 4 , x = 2 , y = 1 ; Console . WriteLine ( findMinimumCost ( n , x , y ) ) ; } }
Minimum steps to reach any of the boundary edges of a matrix | Set 1 | C # program to find Minimum steps to reach any of the boundary edges of a matrix ; Function to find out minimum steps ; boundary edges reached ; already had a route through this point , hence no need to re - visit ; visiting a position ; vertically up ; horizontally right ; horizontally left ; vertically down ; minimum of every path ; Function that returns the minimum steps ; index to store the location at which you are standing ; find '2' in the matrix ; Initialize dp matrix with - 1 ; Initialize vis matrix with false ; Call function to find out minimum steps using memoization and recursion ; if not possible ; Driver Code
using System ; class Solution { static int r = 4 , c = 5 ; static int findMinSteps ( int [ , ] mat , int n , int m , int [ , ] dp , bool [ , ] vis ) { if ( n == 0 || m == 0 || n == ( r - 1 ) || m == ( c - 1 ) ) { return 0 ; } if ( dp [ n , m ] != - 1 ) return dp [ n , m ] ; vis [ n , m ] = true ; int ans1 , ans2 , ans3 , ans4 ; ans1 = ans2 = ans3 = ans4 = ( int ) 1e9 ; if ( mat [ n - 1 , m ] == 0 ) { if ( ! vis [ n - 1 , m ] ) ans1 = 1 + findMinSteps ( mat , n - 1 , m , dp , vis ) ; } if ( mat [ n , m + 1 ] == 0 ) { if ( ! vis [ n , m + 1 ] ) ans2 = 1 + findMinSteps ( mat , n , m + 1 , dp , vis ) ; } if ( mat [ n , m - 1 ] == 0 ) { if ( ! vis [ n , m - 1 ] ) ans3 = 1 + findMinSteps ( mat , n , m - 1 , dp , vis ) ; } if ( mat [ n + 1 , m ] == 0 ) { if ( ! vis [ n + 1 , m ] ) ans4 = 1 + findMinSteps ( mat , n + 1 , m , dp , vis ) ; } dp [ n , m ] = Math . Min ( ans1 , Math . Min ( ans2 , Math . Min ( ans3 , ans4 ) ) ) ; return dp [ n , m ] ; } static int minimumSteps ( int [ , ] mat , int n , int m ) { int twox = - 1 ; int twoy = - 1 ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < m ; j ++ ) { if ( mat [ i , j ] == 2 ) { twox = i ; twoy = j ; break ; } } if ( twox != - 1 ) break ; } int [ , ] dp = new int [ r , r ] ; for ( int j = 0 ; j < r ; j ++ ) for ( int i = 0 ; i < r ; i ++ ) dp [ j , i ] = - 1 ; bool [ , ] vis = new bool [ r , r ] ; for ( int j = 0 ; j < r ; j ++ ) for ( int i = 0 ; i < r ; i ++ ) vis [ j , i ] = false ; int res = findMinSteps ( mat , twox , twoy , dp , vis ) ; if ( res >= 1e9 ) return - 1 ; else return res ; } public static void Main ( ) { int [ , ] mat = { { 1 , 1 , 1 , 0 , 1 } , { 1 , 0 , 2 , 0 , 1 } , { 0 , 0 , 1 , 0 , 1 } , { 1 , 0 , 1 , 1 , 0 } , } ; Console . WriteLine ( minimumSteps ( mat , r , c ) ) ; } }
Count the number of special permutations | C # program to count the number of required permutations ; Function to return the number of ways to choose r objects out of n objects ; Function to return the number of derangements of n ; Function to return the required number of permutations ; Ways to choose i indices from n indices ; Dearangements of ( n - i ) indices System . out . println ( ans ) ; ; Driver Code to test above functions
using System ; public class GFG { static int nCr ( int n , int r ) { int ans = 1 ; if ( r > n - r ) r = n - r ; for ( int i = 0 ; i < r ; i ++ ) { ans *= ( n - i ) ; ans /= ( i + 1 ) ; } return ans ; } static int countDerangements ( int n ) { int [ ] der = new int [ n + 3 ] ; der [ 0 ] = 1 ; der [ 1 ] = 0 ; der [ 2 ] = 1 ; for ( int i = 3 ; i <= n ; i ++ ) der [ i ] = ( i - 1 ) * ( der [ i - 1 ] + der [ i - 2 ] ) ; return der [ n ] ; } static int countPermutations ( int n , int k ) { int ans = 0 ; for ( int i = n - k ; i <= n ; i ++ ) { int ways = nCr ( n , i ) ; ans += ( ways * countDerangements ( n - i ) ) ; } return ans ; } public static void Main ( ) { int n = 5 , k = 3 ; Console . WriteLine ( countPermutations ( n , k ) ) ; } }
Paths with maximum number of ' a ' from ( 1 , 1 ) to ( X , Y ) vertically or horizontally | C # program to find paths with maximum number of ' a ' from ( 1 , 1 ) to ( X , Y ) vertically or horizontally ; Function to answer queries ; Iterate till query ; Decrease to get 0 - based indexing ; Print answer ; Function that pre - computes the dp array ; Check fo the first character ; Iterate in row and columns ; If not first row or not first column ; Not first row ; Not first column ; If it is not ' a ' then increase by 1 ; Driver code ; character N X N array ; queries ; number of queries ; function call to pre - compute ; function call to answer every query
using System ; class GFG { class pair { public int first , second ; public pair ( int first , int second ) { this . first = first ; this . second = second ; } } static int n = 3 ; static int [ , ] dp = new int [ n , n ] ; static void answerQueries ( pair [ ] queries , int q ) { for ( int i = 0 ; i < q ; i ++ ) { int x = queries [ i ] . first ; x -- ; int y = queries [ i ] . second ; y -- ; Console . WriteLine ( dp [ x , y ] ) ; } } static void pre_compute ( char [ , ] a ) { if ( a [ 0 , 0 ] == ' a ' ) dp [ 0 , 0 ] = 0 ; else dp [ 0 , 0 ] = 1 ; for ( int row = 0 ; row < n ; row ++ ) { for ( int col = 0 ; col < n ; col ++ ) { if ( row != 0 col != 0 ) dp [ row , col ] = int . MaxValue ; if ( row != 0 ) { dp [ row , col ] = Math . Min ( dp [ row , col ] , dp [ row - 1 , col ] ) ; } if ( col != 0 ) { dp [ row , col ] = Math . Min ( dp [ row , col ] , dp [ row , col - 1 ] ) ; } if ( a [ row , col ] != ' a ' && ( row != 0 col != 0 ) ) dp [ row , col ] += 1 ; } } } public static void Main ( String [ ] args ) { char [ , ] a = { { ' a ' , ' b ' , ' a ' } , { ' a ' , ' c ' , ' d ' } , { ' b ' , ' a ' , ' b ' } } ; pair [ ] queries = { new pair ( 1 , 3 ) , new pair ( 3 , 3 ) } ; int q = 2 ; pre_compute ( a ) ; answerQueries ( queries , q ) ; } }
Ways to place K bishops on an NÃ — N chessboard so that no two attack | C # implementation of the approach ; returns the number of squares in diagonal i ; returns the number of ways to fill a n * n chessboard with k bishops so that no two bishops attack each other . ; return 0 if the number of valid places to be filled is less than the number of bishops ; dp table to store the values ; Setting the base conditions ; calculate the required number of ways ; stores the answer ; Driver code
using System ; class GFG { static int squares ( int i ) { if ( ( i & 1 ) == 1 ) return i / 4 * 2 + 1 ; else return ( i - 1 ) / 4 * 2 + 2 ; } static long bishop_placements ( int n , int k ) { if ( k > 2 * n - 1 ) return 0 ; long [ , ] dp = new long [ n * 2 , k + 1 ] ; for ( int i = 0 ; i < n * 2 ; i ++ ) dp [ i , 0 ] = 1 ; dp [ 1 , 1 ] = 1 ; for ( int i = 2 ; i < n * 2 ; i ++ ) { for ( int j = 1 ; j <= k ; j ++ ) dp [ i , j ] = dp [ i - 2 , j ] + dp [ i - 2 , j - 1 ] * ( squares ( i ) - j + 1 ) ; } long ans = 0 ; for ( int i = 0 ; i <= k ; i ++ ) { ans += dp [ n * 2 - 1 , i ] * dp [ n * 2 - 2 , k - i ] ; } return ans ; } static public void Main ( ) { int n = 2 ; int k = 2 ; long ans = bishop_placements ( n , k ) ; Console . WriteLine ( ans ) ; } }
Number of ways to partition a string into two balanced subsequences | C # implementation of the approach ; For maximum length of input string ; Declaring the DP table ; Declaring the prefix array ; Function to calculate the number of valid assignments ; Return 1 if X is balanced . ; Increment the count if it an opening bracket ; Decrement the count if it a closing bracket ; Driver code ; Initializing the DP table ; Creating the prefix array ; Initial value for c_x and c_y is zero
using System ; public class GFG { static int MAX = 10 ; static int [ , ] F = new int [ MAX , MAX ] ; static int [ ] C = new int [ MAX ] ; static int noOfAssignments ( string S , int n , int i , int c_x ) { if ( F [ i , c_x ] != - 1 ) { return F [ i , c_x ] ; } if ( i == n ) { if ( c_x == 1 ) { F [ i , c_x ] = 0 ; } else { F [ i , c_x ] = 1 ; } return F [ i , c_x ] ; } int c_y = C [ i ] - c_x ; if ( S [ i ] == ' ( ' ) { F [ i , c_x ] = noOfAssignments ( S , n , i + 1 , c_x + 1 ) + noOfAssignments ( S , n , i + 1 , c_x ) ; return F [ i , c_x ] ; } F [ i , c_x ] = 0 ; if ( c_x == 1 ) { F [ i , c_x ] += noOfAssignments ( S , n , i + 1 , c_x - 1 ) ; } if ( c_y == 1 ) { F [ i , c_x ] += noOfAssignments ( S , n , i + 1 , c_x ) ; } return F [ i , c_x ] ; } public static void Main ( ) { string S = " ( ) " ; int n = S . Length ; for ( int i = 0 ; i < MAX ; i ++ ) { for ( int j = 0 ; j < MAX ; j ++ ) { F [ i , j ] = - 1 ; } } C [ 0 ] = 0 ; for ( int i = 0 ; i < n ; ++ i ) { if ( S [ i ] == ' ( ' ) { C [ i + 1 ] = C [ i ] + 1 ; } else { C [ i + 1 ] = C [ i ] - 1 ; } } Console . WriteLine ( noOfAssignments ( S , n , 0 , 0 ) ) ; } }
Minimum sum falling path in a NxN grid | C # Program to minimum required sum ; Function to return minimum path falling sum ; R = Row and C = Column We begin from second last row and keep adding maximum sum . ; best = min ( A [ R + 1 , C - 1 ] , A [ R + 1 , C ] , A [ R + 1 , C + 1 ] ) ; Driver program ; function to print required answer
using System ; class GFG { static int n = 3 ; static int minFallingPathSum ( int [ , ] A ) { for ( int R = n - 2 ; R >= 0 ; -- R ) { for ( int C = 0 ; C < n ; ++ C ) { int best = A [ R + 1 , C ] ; if ( C > 0 ) best = Math . Min ( best , A [ R + 1 , C - 1 ] ) ; if ( C + 1 < n ) best = Math . Min ( best , A [ R + 1 , C + 1 ] ) ; A [ R , C ] = A [ R , C ] + best ; } } int ans = int . MaxValue ; for ( int i = 0 ; i < n ; ++ i ) ans = Math . Min ( ans , A [ 0 , i ] ) ; return ans ; } public static void Main ( ) { int [ , ] A = { { 1 , 2 , 3 } , { 4 , 5 , 6 } , { 7 , 8 , 9 } } ; Console . WriteLine ( minFallingPathSum ( A ) ) ; } }
Find the maximum sum of Plus shape pattern in a 2 | C # program to find the maximum value of a + shaped pattern in 2 - D array ; Function to return maximum Plus value ; Initializing answer with the minimum value ; Initializing all four arrays ; Initializing left and up array . ; Initializing right and down array . ; calculating value of maximum Plus ( + ) sign ; Driver code ; Function call to find maximum value
using System ; class GFG { public static int N = 100 ; public static int n = 3 , m = 4 ; public static int maxPlus ( int [ , ] arr ) { int ans = int . MinValue ; int [ , ] left = new int [ N , N ] ; int [ , ] right = new int [ N , N ] ; int [ , ] up = new int [ N , N ] ; int [ , ] down = new int [ N , N ] ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < m ; j ++ ) { left [ i , j ] = Math . Max ( 0 , ( ( j != 0 ) ? left [ i , j - 1 ] : 0 ) ) + arr [ i , j ] ; up [ i , j ] = Math . Max ( 0 , ( ( i != 0 ) ? up [ i - 1 , j ] : 0 ) ) + arr [ i , j ] ; } } for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < m ; j ++ ) { right [ i , j ] = Math . Max ( 0 , ( j + 1 == m ? 0 : right [ i , j + 1 ] ) ) + arr [ i , j ] ; down [ i , j ] = Math . Max ( 0 , ( i + 1 == n ? 0 : down [ i + 1 , j ] ) ) + arr [ i , j ] ; } } for ( int i = 1 ; i < n - 1 ; ++ i ) for ( int j = 1 ; j < m - 1 ; ++ j ) ans = Math . Max ( ans , up [ i - 1 , j ] + down [ i + 1 , j ] + left [ i , j - 1 ] + right [ i , j + 1 ] + arr [ i , j ] ) ; return ans ; } static void Main ( ) { int [ , ] arr = new int [ , ] { { 1 , 1 , 1 , 1 } , { - 6 , 1 , 1 , - 4 } , { 1 , 1 , 1 , 1 } } ; Console . Write ( maxPlus ( arr ) ) ; } }
Total number of different staircase that can made from N boxes | C # program to find the total number of different staircase that can made from N boxes ; Function to find the total number of different staircase that can made from N boxes ; DP table , there are two states . First describes the number of boxes and second describes the step ; Initialize all the elements of the table to zero ; Base case ; When step is equal to 2 ; When step is greater than 2 ; Count the total staircase from all the steps ; Driver Code
using System ; class GFG { static int countStaircases ( int N ) { int [ , ] memo = new int [ N + 5 , N + 5 ] ; for ( int i = 0 ; i <= N ; i ++ ) { for ( int j = 0 ; j <= N ; j ++ ) { memo [ i , j ] = 0 ; } } memo [ 3 , 2 ] = memo [ 4 , 2 ] = 1 ; for ( int i = 5 ; i <= N ; i ++ ) { for ( int j = 2 ; j <= i ; j ++ ) { if ( j == 2 ) { memo [ i , j ] = memo [ i - j , j ] + 1 ; } else { memo [ i , j ] = memo [ i - j , j ] + memo [ i - j , j - 1 ] ; } } } int answer = 0 ; for ( int i = 1 ; i <= N ; i ++ ) answer = answer + memo [ N , i ] ; return answer ; } public static void Main ( ) { int N = 7 ; Console . WriteLine ( countStaircases ( N ) ) ; } }
Find maximum points which can be obtained by deleting elements from array | C # program to find maximum cost after deleting all the elements form the array ; function to return maximum cost obtained ; find maximum element of the array . ; initialize count of all elements to zero . ; calculate frequency of all elements of array . ; stores cost of deleted elements . ; selecting minimum range from L and R . ; finds upto which elements are to be deleted when element num is selected . ; get maximum when selecting element num or not . ; Driver Code ; size of array ; function call to find maximum cost
using System ; class GFG { static int maxCost ( int [ ] a , int n , int l , int r ) { int mx = 0 , k ; for ( int i = 0 ; i < n ; ++ i ) mx = Math . Max ( mx , a [ i ] ) ; int [ ] count = new int [ mx + 1 ] ; for ( int i = 0 ; i < count . Length ; i ++ ) count [ i ] = 0 ; for ( int i = 0 ; i < n ; i ++ ) count [ a [ i ] ] ++ ; int [ ] res = new int [ mx + 1 ] ; res [ 0 ] = 0 ; l = Math . Min ( l , r ) ; for ( int num = 1 ; num <= mx ; num ++ ) { k = Math . Max ( num - l - 1 , 0 ) ; res [ num ] = Math . Max ( res [ num - 1 ] , num * count [ num ] + res [ k ] ) ; } return res [ mx ] ; } public static void Main ( ) { int [ ] a = { 2 , 1 , 2 , 3 , 2 , 2 , 1 } ; int l = 1 , r = 1 ; int n = a . Length ; Console . WriteLine ( maxCost ( a , n , l , r ) ) ; } }
Count the number of ways to traverse a Matrix | C # program using recursive solution to count number of ways to reach mat [ m - 1 ] [ n - 1 ] from mat [ 0 ] [ 0 ] in a matrix mat [ ] [ ] ; Returns The number of way from top - left to mat [ m - 1 ] [ n - 1 ] ; Return 1 if it is the first row or first column ; Recursively find the no of way to reach the last cell . ; Driver Code
using System ; class GFG { public int countPaths ( int m , int n ) { if ( m == 1 n == 1 ) return 1 ; return countPaths ( m - 1 , n ) + countPaths ( m , n - 1 ) ; } public static void Main ( ) { GFG g = new GFG ( ) ; int n = 5 , m = 5 ; Console . WriteLine ( g . countPaths ( n , m ) ) ; Console . Read ( ) ; } }
Count the number of ways to traverse a Matrix | A simple recursive solution to count number of ways to reach mat [ m - 1 ] [ n - 1 ] from mat [ 0 ] [ 0 ] in a matrix mat [ ] [ ] ; Returns The number of way from top - left to mat [ m - 1 ] [ n - 1 ] ; Driver code
using System ; class GFG { static int countPaths ( int m , int n ) { int [ , ] dp = new int [ m + 1 , n + 1 ] ; for ( int i = 1 ; i <= m ; i ++ ) { for ( int j = 1 ; j <= n ; j ++ ) { if ( i == 1 j == 1 ) dp [ i , j ] = 1 ; else dp [ i , j ] = dp [ i - 1 , j ] + dp [ i , j - 1 ] ; } } return dp [ m , n ] ; } public static void Main ( ) { int n = 5 ; int m = 5 ; Console . WriteLine ( countPaths ( n , m ) ) ; } }
Number of ways a convex polygon of n + 2 sides can split into triangles by connecting vertices | C # program to find the nth catalan number ; Returns value of Binomial Coefficient C ( n , k ) ; Since C ( n , k ) = C ( n , n - k ) ; Calculate value of [ n * ( n - 1 ) * -- - * ( n - k + 1 ) ] / [ k * ( k - 1 ) * -- - * 1 ] ; A Binomial coefficient based function to find nth catalan number in O ( n ) time ; Calculate value of 2 nCn ; return 2 nCn / ( n + 1 ) ; Driver code
using System ; class GFG { static long binomialCoeff ( int n , int k ) { long res = 1 ; if ( k > n - k ) k = n - k ; for ( int i = 0 ; i < k ; ++ i ) { res *= ( n - i ) ; res /= ( i + 1 ) ; } return res ; } static long catalan ( int n ) { long c = binomialCoeff ( 2 * n , n ) ; return c / ( n + 1 ) ; } public static void Main ( ) { int n = 3 ; Console . WriteLine ( catalan ( n ) ) ; } }
Alternate Fibonacci Numbers | Alternate Fibonacci Series using Dynamic Programming ; 0 th and 1 st number of the series are 0 and 1 ; Driver Code
using System ; class GFG { static void alternateFib ( int n ) { if ( n < 0 ) return ; int f1 = 0 ; int f2 = 1 ; Console . Write ( f1 + " ▁ " ) ; for ( int i = 2 ; i <= n ; i ++ ) { int f3 = f2 + f1 ; if ( i % 2 == 0 ) Console . Write ( f3 + " ▁ " ) ; f1 = f2 ; f2 = f3 ; } } public static void Main ( ) { int N = 15 ; alternateFib ( N ) ; } }
Number of ways to form an array with distinct adjacent elements | C # program to count the number of ways to form arrays of N numbers such that the first and last numbers are fixed and all consecutive numbers are distinct ; Returns the total ways to form arrays such that every consecutive element is different and each element except the first and last can take values from 1 to M ; define the dp [ ] [ ] array ; if the first element is 1 ; there is only one way to place a 1 at the first index ; the value at first index needs to be 1 , thus there is no way to place a non - one integer ; if the first element was 1 then at index 1 , only non one integer can be placed thus there are M - 1 ways to place a non one integer at index 2 and 0 ways to place a 1 at the 2 nd index ; Else there is one way to place a one at index 2 and if a non one needs to be placed here , there are ( M - 2 ) options , i . e neither the element at this index should be 1 , neither should it be equal to the previous element ; Build the dp array in bottom up manner ; f ( i , one ) = f ( i - 1 , non - one ) ; f ( i , non - one ) = f ( i - 1 , one ) * ( M - 1 ) + f ( i - 1 , non - one ) * ( M - 2 ) ; last element needs to be one , so return dp [ n - 1 ] [ 0 ] ; Driver Code
using System ; class GFG { static int totalWays ( int N , int M , int X ) { int [ , ] dp = new int [ N + 1 , 2 ] ; if ( X == 1 ) { dp [ 0 , 0 ] = 1 ; } else { dp [ 0 , 1 ] = 0 ; } if ( X == 1 ) { dp [ 1 , 0 ] = 0 ; dp [ 1 , 1 ] = M - 1 ; } else { dp [ 1 , 0 ] = 1 ; dp [ 1 , 1 ] = ( M - 2 ) ; } for ( int i = 2 ; i < N ; i ++ ) { dp [ i , 0 ] = dp [ i - 1 , 1 ] ; dp [ i , 1 ] = dp [ i - 1 , 0 ] * ( M - 1 ) + dp [ i - 1 , 1 ] * ( M - 2 ) ; } return dp [ N - 1 , 0 ] ; } public static void Main ( ) { int N = 4 , M = 3 , X = 2 ; Console . WriteLine ( totalWays ( N , M , X ) ) ; } }
Memoization ( 1D , 2D and 3D ) | C # program to find the Nth term of Fibonacci series ; Fibonacci Series using Recursion ; Base case ; recursive calls ; Driver Code
using System ; class GFG { static int fib ( int n ) { if ( n <= 1 ) return n ; return fib ( n - 1 ) + fib ( n - 2 ) ; } static public void Main ( ) { int n = 6 ; Console . WriteLine ( fib ( n ) ) ; } }
Memoization ( 1D , 2D and 3D ) | C # program to find the Nth term of Fibonacci series ; Fibonacci Series using memoized Recursion ; base case ; if fib ( n ) has already been computed we do not do further recursive calls and hence reduce the number of repeated work ; store the computed value of fib ( n ) in an array term at index n to so that it does not needs to be precomputed again ; Driver Code
using System ; class GFG { static int fib ( int n ) { int [ ] term = new int [ 1000 ] ; if ( n <= 1 ) return n ; if ( term [ n ] != 0 ) return term [ n ] ; else { term [ n ] = fib ( n - 1 ) + fib ( n - 2 ) ; return term [ n ] ; } } public static void Main ( ) { int n = 6 ; Console . Write ( fib ( n ) ) ; } }
Memoization ( 1D , 2D and 3D ) | A Naive recursive implementation of LCS problem ; Utility function to get max of 2 integers ; Returns length of LCS for X [ 0. . m - 1 ] , Y [ 0. . n - 1 ] ; Driver Code
using System ; class GFG { static int max ( int a , int b ) { return ( a > b ) ? a : b ; } static int lcs ( string X , string Y , int m , int n ) { if ( m == 0 n == 0 ) return 0 ; if ( X [ m - 1 ] == Y [ n - 1 ] ) return 1 + lcs ( X , Y , m - 1 , n - 1 ) ; else return max ( lcs ( X , Y , m , n - 1 ) , lcs ( X , Y , m - 1 , n ) ) ; } public static void Main ( ) { string X = " AGGTAB " ; string Y = " GXTXAYB " ; int m = X . Length ; int n = Y . Length ; Console . Write ( " Length ▁ of ▁ LCS ▁ is ▁ " + lcs ( X , Y , m , n ) ) ; } }
Smallest number with given sum of digits and sum of square of digits | C # program to find the Smallest number with given sum of digits and sum of square of digits ; Top down dp to find minimum number of digits with given sum of dits a and sum of square of digits as b ; Invalid condition ; Number of digits satisfied ; Memoization ; Initialize ans as maximum as we have to find the minimum number of digits ; Check for all possible combinations of digits ; recurrence call ; If the combination of digits cannot give sum as a and sum of square of digits as b ; Returns the minimum number of digits ; Function to print the digits that gives sum as a and sum of square of digits as b ; initialize the dp array as - 1 ; base condition ; function call to get the minimum number of digits ; When there does not exists any number ; Printing the digits from the most significant digit ; Trying all combinations ; checking conditions for minimum digits ; Driver Code ; Function call to print the smallest number
using System ; public class GFG { static int [ , ] dp = new int [ 901 , 8101 ] ; static int minimumNumberOfDigits ( int a , int b ) { if ( a > b a < 0 b < 0 a > 900 b > 8100 ) { return - 1 ; } if ( a == 0 && b == 0 ) { return 0 ; } if ( dp [ a , b ] != - 1 ) { return dp [ a , b ] ; } int ans = 101 ; for ( int i = 9 ; i >= 1 ; i -- ) { int k = minimumNumberOfDigits ( a - i , b - ( i * i ) ) ; if ( k != - 1 ) { ans = Math . Min ( ans , k + 1 ) ; } } return dp [ a , b ] = ans ; } static void printSmallestNumber ( int a , int b ) { for ( int i = 0 ; i < dp . GetLength ( 0 ) ; i ++ ) for ( int j = 0 ; j < dp . GetLength ( 1 ) ; j ++ ) dp [ i , j ] = - 1 ; dp [ 0 , 0 ] = 0 ; int k = minimumNumberOfDigits ( a , b ) ; if ( k == - 1 k > 100 ) { Console . WriteLine ( " - 1" ) ; } else { while ( a > 0 && b > 0 ) { for ( int i = 1 ; i <= 9 ; i ++ ) { if ( a >= i && b >= i * i && 1 + dp [ a - i , b - i * i ] == dp [ a , b ] ) { Console . Write ( i ) ; a -= i ; b -= i * i ; break ; } } } } } public static void Main ( ) { int a = 18 , b = 162 ; printSmallestNumber ( a , b ) ; } }
Sum of product of consecutive Binomial Coefficients | C # Program to find sum of product of consecutive Binomial Coefficient . ; Find the binomial coefficient up to nth term ; memset ( C , 0 , sizeof ( C ) ) ; C [ 0 ] = 1 ; nC0 is 1 ; Compute next row of pascal triangle using the previous row ; Return the sum of the product of consecutive binomial coefficient . ; Driver Code
using System ; class GFG { static int binomialCoeff ( int n , int k ) { int [ ] C = new int [ k + 1 ] ; for ( int i = 1 ; i <= n ; i ++ ) { for ( int j = Math . Min ( i , k ) ; j > 0 ; j -- ) C [ j ] = C [ j ] + C [ j - 1 ] ; } return C [ k ] ; } static int sumOfproduct ( int n ) { return binomialCoeff ( 2 * n , n - 1 ) ; } static public void Main ( ) { int n = 3 ; Console . WriteLine ( sumOfproduct ( n ) ) ; } }
Check if array sum can be made K by three operations on it | C # Program to find if Array can have a sum of K by applying three types of possible ; Check if it is possible to achieve a sum with three operation allowed . ; If sum is negative . ; If going out of bound . ; If sum is achieved . ; If the current state is not evaluated yet . ; Replacing element with negative value of the element . ; Substracting index number from the element . ; Adding index number to the element . ; Wrapper Function ; Driver Code
using System ; class GFG { static int MAX = 100 ; static int check ( int i , int sum , int n , int k , int [ ] a , int [ , ] dp ) { if ( sum <= 0 ) { return 0 ; } if ( i >= n ) { if ( sum == k ) { return 1 ; } return 0 ; } if ( dp [ i , sum ] != - 1 ) { return dp [ i , sum ] ; } dp [ i , sum ] = check ( i + 1 , sum - 2 * a [ i ] , n , k , a , dp ) | check ( i + 1 , sum , n , k , a , dp ) ; dp [ i , sum ] = check ( i + 1 , sum - ( i + 1 ) , n , k , a , dp ) | dp [ i , sum ] ; dp [ i , sum ] = check ( i + 1 , sum + i + 1 , n , k , a , dp ) | dp [ i , sum ] ; return dp [ i , sum ] ; } static int wrapper ( int n , int k , int [ ] a ) { int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) { sum += a [ i ] ; } int [ , ] dp = new int [ MAX , MAX ] ; for ( int i = 0 ; i < MAX ; i ++ ) { for ( int j = 0 ; j < MAX ; j ++ ) { dp [ i , j ] = - 1 ; } } return check ( 0 , sum , n , k , a , dp ) ; } static public void Main ( ) { int [ ] a = { 1 , 2 , 3 , 4 } ; int n = 4 , k = 5 ; if ( wrapper ( n , k , a ) == 1 ) { Console . WriteLine ( " Yes " ) ; } else { Console . WriteLine ( " No " ) ; } } }
Print Fibonacci sequence using 2 variables | Simple C # Program to print Fibonacci sequence ; Driver code
using System ; class GFG { static void fib ( int n ) { int a = 0 , b = 1 , c ; if ( n >= 0 ) Console . Write ( a + " ▁ " ) ; if ( n >= 1 ) Console . Write ( b + " ▁ " ) ; for ( int i = 2 ; i <= n ; i ++ ) { c = a + b ; Console . Write ( c + " ▁ " ) ; a = b ; b = c ; } } public static void Main ( ) { fib ( 9 ) ; } }
Maximum sum increasing subsequence from a prefix and a given element after prefix is must | C # program to find maximum sum increasing subsequence till i - th index and including k - th index . ; Initializing the first row of the dp [ ] [ ] . ; Creating the dp [ ] [ ] matrix . ; To calculate for i = 4 and k = 6. ; Driver code
using System ; class GFG { static int pre_compute ( int [ ] a , int n , int index , int k ) { int [ , ] dp = new int [ n , n ] ; for ( int i = 0 ; i < n ; i ++ ) { if ( a [ i ] > a [ 0 ] ) dp [ 0 , i ] = a [ i ] + a [ 0 ] ; else dp [ 0 , i ] = a [ i ] ; } for ( int i = 1 ; i < n ; i ++ ) { for ( int j = 0 ; j < n ; j ++ ) { if ( a [ j ] > a [ i ] && j > i ) { if ( dp [ i - 1 , i ] + a [ j ] > dp [ i - 1 , j ] ) dp [ i , j ] = dp [ i - 1 , i ] + a [ j ] ; else dp [ i , j ] = dp [ i - 1 , j ] ; } else dp [ i , j ] = dp [ i - 1 , j ] ; } } return dp [ index , k ] ; } static public void Main ( ) { int [ ] a = { 1 , 101 , 2 , 3 , 100 , 4 , 5 } ; int n = a . Length ; int index = 4 , k = 6 ; Console . WriteLine ( pre_compute ( a , n , index , k ) ) ; } }
Moser | C # code to generate first ' n ' terms of the Moser - de Bruijn Sequence ; Function to generate nth term of Moser - de Bruijn Sequence ; S ( 2 * n ) = 4 * S ( n ) ; S ( 2 * n + 1 ) = 4 * S ( n ) + 1 ; Generating the first ' n ' terms of Moser - de Bruijn Sequence ; Driver Code
using System ; class GFG { static int gen ( int n ) { int [ ] S = new int [ n + 1 ] ; S [ 0 ] = 0 ; if ( n != 0 ) S [ 1 ] = 1 ; for ( int i = 2 ; i <= n ; i ++ ) { if ( i % 2 == 0 ) S [ i ] = 4 * S [ i / 2 ] ; else S [ i ] = 4 * S [ i / 2 ] + 1 ; } return S [ n ] ; } static void moserDeBruijn ( int n ) { for ( int i = 0 ; i < n ; i ++ ) Console . Write ( gen ( i ) + " ▁ " ) ; } public static void Main ( ) { int n = 15 ; Console . WriteLine ( " First ▁ " + n + " ▁ terms ▁ of ▁ " + " Moser - de ▁ Bruijn ▁ Sequence ▁ : ▁ " ) ; moserDeBruijn ( n ) ; } }
Longest Common Substring ( Space optimized DP solution ) | Space optimized C # implementation of longest common substring . ; Function to find longest common substring . ; Find length of both the strings . ; Variable to store length of longest common substring . ; Matrix to store result of two consecutive rows at a time . ; Variable to represent which row of matrix is current row . ; For a particular value of i and j , len [ currRow ] [ j ] stores length of longest common substring in string X [ 0. . i ] and Y [ 0. . j ] . ; Make current row as previous row and previous row as new current row . ; Driver Code
using System ; using System . Collections . Generic ; class GFG { static int LCSubStr ( string X , string Y ) { int m = X . Length ; int n = Y . Length ; int result = 0 ; int [ , ] len = new int [ 2 , n ] ; int currRow = 0 ; for ( int i = 0 ; i < m ; i ++ ) { for ( int j = 0 ; j < n ; j ++ ) { if ( i == 0 j == 0 ) { len [ currRow , j ] = 0 ; } else if ( X [ i - 1 ] == Y [ j - 1 ] ) { len [ currRow , j ] = len [ ( 1 - currRow ) , ( j - 1 ) ] + 1 ; result = Math . Max ( result , len [ currRow , j ] ) ; } else { len [ currRow , j ] = 0 ; } } currRow = 1 - currRow ; } return result ; } public static void Main ( ) { string X = " GeeksforGeeks " ; string Y = " GeeksQuiz " ; Console . Write ( LCSubStr ( X , Y ) ) ; } }
Minimal moves to form a string by adding characters or appending string itself | C # program to print the Minimal moves to form a string by appending string and adding characters ; function to return the minimal number of moves ; initializing dp [ i ] to INT_MAX ; initialize both strings to null ; base case ; check if it can be appended ; addition of character takes one step ; appending takes 1 step , and we directly reach index i * 2 + 1 after appending so the number of steps is stord in i * 2 + 1 ; Driver Code ; function call to return minimal number of moves
using System ; class GFG { static int minimalSteps ( String s , int n ) { int [ ] dp = new int [ n ] ; for ( int i = 0 ; i < n ; i ++ ) dp [ i ] = int . MaxValue ; String s1 = " " , s2 = " " ; dp [ 0 ] = 1 ; s1 += s [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) { s1 += s [ i ] ; s2 = s . Substring ( i , 1 ) ; dp [ i ] = Math . Min ( dp [ i ] , dp [ i - 1 ] + 1 ) ; if ( s1 == s2 ) dp [ i * 2 + 1 ] = Math . Min ( dp [ i ] + 1 , dp [ i * 2 + 1 ] ) ; } return dp [ n - 1 ] ; } public static void Main ( String [ ] args ) { String s = " aaaaaaaa " ; int n = s . Length ; Console . Write ( minimalSteps ( s , n ) / 2 ) ; } }
Check if any valid sequence is divisible by M | C # program for the above approach ; Function to check if any valid sequence is divisible by M ; Declare mod array ; Calculate the mod array ; Check if sum is divisible by M ; Check if sum is not divisible by 2 ; Remove the first element from the ModArray since it is not possible to place minus on the first element ; Decrease the size of array ; Sort the array ; Loop until the pointer cross each other ; Check if sum becomes equal ; Increase and decrease the pointer accordingly ; Driver code ; Function call
using System . Collections . Generic ; using System ; class GFG { static void func ( int n , int m , int [ ] A ) { List < int > ModArray = new List < int > ( ) ; for ( int i = 0 ; i < n ; i ++ ) ModArray . Add ( 0 ) ; int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) { ModArray [ i ] = ( A [ i ] % m ) ; sum += ( ( int ) ModArray [ i ] ) ; } sum = sum % m ; if ( sum % m == 0 ) { Console . WriteLine ( " True " ) ; return ; } if ( sum % 2 != 0 ) { Console . WriteLine ( " False " ) ; } else { ModArray . Remove ( 0 ) ; int i = 0 ; int j = ModArray . Count - 1 ; ModArray . Sort ( ) ; sum = sum / 2 ; int i1 , i2 ; while ( i <= j ) { int s = ( int ) ModArray [ i ] + ( int ) ModArray [ j ] ; if ( s == sum ) { i1 = i ; i2 = j ; Console . WriteLine ( " True " ) ; break ; } else if ( s > sum ) j -- ; else i ++ ; } } } public static void Main ( ) { int m = 2 ; int [ ] a = { 1 , 3 , 9 } ; int n = a . Length ; func ( n , m , a ) ; } }
Golomb sequence | C # Program to find first n terms of Golomb sequence . ; Print the first n term of Golomb Sequence ; base cases ; Finding and printing first n terms of Golomb Sequence . ; Driver Code
using System ; class GFG { static void printGolomb ( int n ) { int [ ] dp = new int [ n + 1 ] ; dp [ 1 ] = 1 ; Console . Write ( dp [ 1 ] + " ▁ " ) ; for ( int i = 2 ; i <= n ; i ++ ) { dp [ i ] = 1 + dp [ i - dp [ dp [ i - 1 ] ] ] ; Console . Write ( dp [ i ] + " ▁ " ) ; } } public static void Main ( ) { int n = 9 ; printGolomb ( n ) ; } }
Balanced expressions such that given positions have opening brackets | C # code to find number of ways of arranging bracket with proper expressions ; function to calculate the number of proper bracket sequence ; hash array to mark the positions of opening brackets ; dp 2d array ; mark positions in hash array ; first position marked as 1 ; iterate and formulate the recurrences ; if position has a opening bracket ; return answer ; driver code ; positions where opening braces will be placed
using System ; class GFG { static int N = 1000 ; public static long arrangeBraces ( int n , int [ ] pos , int k ) { bool [ ] h = new bool [ N ] ; int [ , ] dp = new int [ N , N ] ; for ( int i = 0 ; i < N ; i ++ ) h [ i ] = false ; for ( int i = 0 ; i < N ; i ++ ) for ( int j = 0 ; j < N ; j ++ ) dp [ i , j ] = 0 ; for ( int i = 0 ; i < k ; i ++ ) h [ pos [ i ] ] = true ; dp [ 0 , 0 ] = 1 ; for ( int i = 1 ; i <= 2 * n ; i ++ ) { for ( int j = 0 ; j <= 2 * n ; j ++ ) { if ( h [ i ] ) { if ( j != 0 ) dp [ i , j ] = dp [ i - 1 , j - 1 ] ; else dp [ i , j ] = 0 ; } else { if ( j != 0 ) dp [ i , j ] = dp [ i - 1 , j - 1 ] + dp [ i - 1 , j + 1 ] ; else dp [ i , j ] = dp [ i - 1 , j + 1 ] ; } } } return dp [ 2 * n , 0 ] ; } static void Main ( ) { int n = 3 ; int [ ] pos = new int [ ] { 2 } ; int k = pos . Length ; Console . Write ( arrangeBraces ( n , pos , k ) ) ; } }
Maximum difference of zeros and ones in binary string | Set 2 ( O ( n ) time ) | C # Program to find the length of substring with maximum difference of zeroes and ones in binary string . ; Find the length of substring with maximum difference of zeros and ones in binary string ; traverse a binary string from left to right ; add current value to the current_sum according to the Character if it ' s ▁ ' 0 ' add 1 else -1 ; update maximum sum ; return - 1 if string does not contain any zero that means string contains all ones otherwise max_sum ; Driver Code
using System ; class GFG { public static int findLength ( string str , int n ) { int current_sum = 0 ; int max_sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) { current_sum += ( str [ i ] == '0' ? 1 : - 1 ) ; if ( current_sum < 0 ) { current_sum = 0 ; } max_sum = Math . Max ( current_sum , max_sum ) ; } return max_sum == 0 ? - 1 : max_sum ; } public static void Main ( string [ ] args ) { string str = "11000010001" ; int n = str . Length ; Console . WriteLine ( findLength ( str , n ) ) ; } }
Number of decimal numbers of length k , that are strict monotone | C # program to count numbers of k digits that are strictly monotone . ; DP [ i ] [ j ] is going to store monotone numbers of length i + 1 considering j + 1 digits ( 1 , 2 , 3 , . .9 ) ; Unit length numbers ; Building dp [ ] in bottom up ; Driver code
using System ; class GFG { static int DP_s = 9 ; static int getNumStrictMonotone ( int len ) { int [ , ] DP = new int [ len , DP_s ] ; for ( int i = 0 ; i < DP_s ; ++ i ) DP [ 0 , i ] = i + 1 ; for ( int i = 1 ; i < len ; ++ i ) for ( int j = 1 ; j < DP_s ; ++ j ) DP [ i , j ] = DP [ i - 1 , j - 1 ] + DP [ i , j - 1 ] ; return DP [ len - 1 , DP_s - 1 ] ; } public static void Main ( ) { int n = 2 ; Console . WriteLine ( getNumStrictMonotone ( n ) ) ; } }
Count ways to divide circle using N non | C # code to count ways to divide circle using N non - intersecting chords . ; n = no of points required ; dp array containing the sum ; returning the required number ; Driver code
using System ; class GFG { static int chordCnt ( int A ) { int n = 2 * A ; int [ ] dpArray = new int [ n + 1 ] ; dpArray [ 0 ] = 1 ; dpArray [ 2 ] = 1 ; for ( int i = 4 ; i <= n ; i += 2 ) { for ( int j = 0 ; j < i - 1 ; j += 2 ) { dpArray [ i ] += ( dpArray [ j ] * dpArray [ i - 2 - j ] ) ; } } return dpArray [ n ] ; } public static void Main ( ) { int N ; N = 2 ; Console . WriteLine ( chordCnt ( N ) ) ; N = 1 ; Console . WriteLine ( chordCnt ( N ) ) ; N = 4 ; Console . WriteLine ( chordCnt ( N ) ) ; } }
Check for possible path in 2D matrix | C # program to find if there is path from top left to right bottom ; to find the path from top left to bottom right ; set arr [ 0 ] [ 0 ] = 1 ; Mark reachable ( from top left ) nodes in first row and first column . ; Mark reachable nodes in remaining matrix . ; return yes if right bottom index is 1 ; Driver code ; Given array ; path from arr [ 0 ] [ 0 ] to arr [ row ] [ col ]
using System ; class GFG { static bool isPath ( int [ , ] arr ) { arr [ 0 , 0 ] = 1 ; for ( int i = 1 ; i < 5 ; i ++ ) if ( arr [ i , 0 ] != - 1 ) arr [ i , 0 ] = arr [ i - 1 , 0 ] ; for ( int j = 1 ; j < 5 ; j ++ ) if ( arr [ 0 , j ] != - 1 ) arr [ 0 , j ] = arr [ 0 , j - 1 ] ; for ( int i = 1 ; i < 5 ; i ++ ) for ( int j = 1 ; j < 5 ; j ++ ) if ( arr [ i , j ] != - 1 ) arr [ i , j ] = Math . Max ( arr [ i , j - 1 ] , arr [ i - 1 , j ] ) ; return ( arr [ 5 - 1 , 5 - 1 ] == 1 ) ; } public static void Main ( ) { int [ , ] arr = { { 0 , 0 , 0 , - 1 , 0 } , { - 1 , 0 , 0 , - 1 , - 1 } , { 0 , 0 , 0 , - 1 , 0 } , { - 1 , 0 , - 1 , 0 , - 1 } , { 0 , 0 , - 1 , 0 , 0 } } ; if ( isPath ( arr ) ) Console . WriteLine ( " Yes " ) ; else Console . WriteLine ( " No " ) ; } }
NewmanΓ’ β‚¬β€œ ShanksΓ’ β‚¬β€œ Williams prime | C # Program to find Newman - Shanks - Williams prime ; return nth Newman - Shanks - Williams prime ; Base case ; Recursive step ; Driver code
using System ; class GFG { static int nswp ( int n ) { if ( n == 0 n == 1 ) return 1 ; return 2 * nswp ( n - 1 ) + nswp ( n - 2 ) ; } public static void Main ( ) { int n = 3 ; Console . WriteLine ( nswp ( n ) ) ; } }
Newman Shanks Williams prime | C # Program to find Newman Shanks Williams prime ; return nth Newman Shanks Williams prime ; Base case ; Finding nth Newman Shanks Williams prime ; Driver Program
using System ; class GFG { static int nswp ( int n ) { int [ ] dp = new int [ n + 1 ] ; dp [ 0 ] = dp [ 1 ] = 1 ; for ( int i = 2 ; i <= n ; i ++ ) dp [ i ] = 2 * dp [ i - 1 ] + dp [ i - 2 ] ; return dp [ n ] ; } public static void Main ( ) { int n = 3 ; Console . WriteLine ( nswp ( n ) ) ; } }
Number of ways to insert a character to increase the LCS by one | C # Program for Number of ways to insert a character to increase LCS by one ; Return the Number of ways to insert a character to increase the longest Common Subsequence by one ; Insert all positions of all characters in string B . ; longest Common Subsequence ; longest Common Subsequence from reverse ; inserting character between position i and i + 1 ; Driver Code
using System ; using System . Collections . Generic ; class GFG { static readonly int MAX = 256 ; static int numberofways ( String A , String B , int N , int M ) { List < int > [ ] pos = new List < int > [ MAX ] ; for ( int i = 0 ; i < MAX ; i ++ ) pos [ i ] = new List < int > ( ) ; for ( int i = 0 ; i < M ; i ++ ) pos [ B [ i ] ] . Add ( i + 1 ) ; int [ , ] dpl = new int [ N + 2 , M + 2 ] ; for ( int i = 1 ; i <= N ; i ++ ) { for ( int j = 1 ; j <= M ; j ++ ) { if ( A [ i - 1 ] == B [ j - 1 ] ) dpl [ i , j ] = dpl [ i - 1 , j - 1 ] + 1 ; else dpl [ i , j ] = Math . Max ( dpl [ i - 1 , j ] , dpl [ i , j - 1 ] ) ; } } int LCS = dpl [ N , M ] ; int [ , ] dpr = new int [ N + 2 , M + 2 ] ; for ( int i = N ; i >= 1 ; i -- ) { for ( int j = M ; j >= 1 ; j -- ) { if ( A [ i - 1 ] == B [ j - 1 ] ) dpr [ i , j ] = dpr [ i + 1 , j + 1 ] + 1 ; else dpr [ i , j ] = Math . Max ( dpr [ i + 1 , j ] , dpr [ i , j + 1 ] ) ; } } int ans = 0 ; for ( int i = 0 ; i <= N ; i ++ ) { for ( int j = 0 ; j < MAX ; j ++ ) { foreach ( int x in pos [ j ] ) { if ( dpl [ i , x - 1 ] + dpr [ i + 1 , x + 1 ] == LCS ) { ans ++ ; break ; } } } } return ans ; } public static void Main ( String [ ] args ) { String A = " aa " , B = " baaa " ; int N = A . Length , M = B . Length ; Console . WriteLine ( numberofways ( A , B , N , M ) ) ; } }
Minimum cost to make two strings identical by deleting the digits | C # code to find minimum cost to make two strings identical ; Function to returns cost of removing the identical characters in LCS for X [ 0. . m - 1 ] , Y [ 0. . n - 1 ] ; Following steps build L [ m + 1 ] [ n + 1 ] in bottom up fashion . Note that L [ i ] [ j ] contains cost of removing identical characters in LCS of X [ 0. . i - 1 ] and Y [ 0. . j - 1 ] ; If both characters are same , add both of them ; Otherwise find the maximum cost among them ; Returns cost of making X [ ] and Y [ ] identical ; Find LCS of X [ ] and Y [ ] ; Initialize the cost variable ; Find cost of all characters in both strings ; Driver function
using System ; public class GfG { static int lcs ( string X , string Y , int m , int n ) { int [ , ] L = new int [ m + 1 , n + 1 ] ; for ( int i = 0 ; i <= m ; ++ i ) { for ( int j = 0 ; j <= n ; j ++ ) { if ( i == 0 j == 0 ) L [ i , j ] = 0 ; else if ( X [ i - 1 ] == Y [ j - 1 ] ) L [ i , j ] = L [ i - 1 , j - 1 ] + 2 * ( X [ i - 1 ] - '0' ) ; else L [ i , j ] = L [ i - 1 , j ] > L [ i , j - 1 ] ? L [ i - 1 , j ] : L [ i , j - 1 ] ; } } return L [ m , n ] ; } static int findMinCost ( string X , string Y ) { int m = X . Length , n = Y . Length ; int cost = 0 ; for ( int i = 0 ; i < m ; ++ i ) cost += X [ i ] - '0' ; for ( int i = 0 ; i < n ; ++ i ) cost += Y [ i ] - '0' ; return cost - lcs ( X , Y , m , n ) ; } public static void Main ( ) { string X = "3759" ; string Y = "9350" ; Console . WriteLine ( " Minimum ▁ Cost ▁ to ▁ make ▁ two ▁ strings " + " ▁ identical ▁ is ▁ = ▁ " + findMinCost ( X , Y ) ) ; } }
Given a large number , check if a subsequence of digits is divisible by 8 | C # program to check if a subsequence of digits is divisible by 8. ; Function to calculate any permutation divisible by 8. If such permutation exists , the function will return that permutation else it will return - 1 ; Converting string to integer array for ease of computations ( Indexing in arr [ ] is considered to be starting from 1 ) ; Generating all possible permutations and checking if any such permutation is divisible by 8 ; Driver function
using System ; class GFG { static bool isSubSeqDivisible ( string str ) { int i , j , k , l = str . Length ; int [ ] arr = new int [ l ] ; for ( i = 0 ; i < n ; i ++ ) arr [ i ] = str [ i ] - '0' ; for ( i = 0 ; i < l ; i ++ ) { for ( j = i ; j < l ; j ++ ) { for ( k = j ; k < l ; k ++ ) { if ( arr [ i ] % 8 == 0 ) return true ; else if ( ( arr [ i ] * 10 + arr [ j ] ) % 8 == 0 && i != j ) return true ; else if ( ( arr [ i ] * 100 + arr [ j ] * 10 + arr [ k ] ) % 8 == 0 && i != j && j != k && i != k ) return true ; } } } return false ; } public static void Main ( ) { string str = "3144" ; if ( isSubSeqDivisible ( str ) ) Console . WriteLine ( " Yes " ) ; else Console . WriteLine ( " No " ) ; } }
Given a large number , check if a subsequence of digits is divisible by 8 | C # program to find if there is a subsequence of digits divisible by 8. ; Function takes in an array of numbers , dynamically goes on the location and makes combination of numbers . ; Converting string to integer array for ease of computations ( Indexing in arr [ ] is considered to be starting from 1 ) ; If we consider the number in our combination , we add it to the previous combination ; If we exclude the number from our combination ; If at dp [ i ] [ 0 ] , we find value 1 / true , it shows that the number exists at the value of ' i ' ; Driver function
using System ; class GFG { static bool isSubSeqDivisible ( String str ) { int n = str . Length ; int [ , ] dp = new int [ n + 1 , 10 ] ; int [ ] arr = new int [ n + 1 ] ; for ( int i = 1 ; i <= n ; i ++ ) arr [ i ] = ( int ) ( str [ i - 1 ] - '0' ) ; for ( int i = 1 ; i <= n ; i ++ ) { dp [ i , arr [ i ] % 8 ] = 1 ; for ( int j = 0 ; j < 8 ; j ++ ) { if ( dp [ i - 1 , j ] > dp [ i , ( j * 10 + arr [ i ] ) % 8 ] ) dp [ i , ( j * 10 + arr [ i ] ) % 8 ] = dp [ i - 1 , j ] ; if ( dp [ i - 1 , j ] > dp [ i , j ] ) dp [ i , j ] = dp [ i - 1 , j ] ; } } for ( int i = 1 ; i <= n ; i ++ ) { if ( dp [ i , 0 ] == 1 ) return true ; } return false ; } public static void Main ( ) { string str = "3144" ; if ( isSubSeqDivisible ( str ) ) Console . WriteLine ( " Yes " ) ; else Console . WriteLine ( " No " ) ; } }