"Longest sub | C # implementation of the approach ; Function to return the length of the largest subsequence with non - negative sum ; To store the current sum ; Sort the input array in non - increasing order ; Traverse through the array ; Add the current element to the sum ; Condition when c_sum falls below zero ; Complete array has a non - negative sum ; Driver code"
Solution in C#:

using System ; class GFG { static int maxLen ( int [ ] arr , int n ) { int c_sum = 0 ; Array . Sort ( arr ) ; for ( int i = n - 1 ; i >= 0 ; i -- ) { c_sum += arr [ i ] ; if ( c_sum < 0 ) return i ; } return n ; } public static void Main ( String [ ] args ) { int [ ] arr = { 3 , 5 , - 6 } ; int n = arr . Length ; Console . WriteLine ( maxLen ( arr , n ) ) ; } }


"Longest sub | C # implementation of the approach ; Function to return the length of the longest required sub - sequence ; Find the maximum element from the array ; Insert all lucas numbers below max to the set a and b are first two elements of the Lucas sequence ; If current element is a Lucas number , increment count ; Return the count ; Driver code"
Solution in C#:

using System ; using System . Collections . Generic ; using System . Linq ; class GFG { static int LucasSequence ( int [ ] arr , int n ) { int max = arr . Max ( ) ; int counter = 0 ; HashSet < int > s = new HashSet < int > ( ) ; int a = 2 , b = 1 ; s . Add ( a ) ; s . Add ( b ) ; while ( b < max ) { int c = a + b ; a = b ; b = c ; s . Add ( b ) ; } for ( int i = 0 ; i < n ; i ++ ) { if ( s . Contains ( arr [ i ] ) ) counter ++ ; } return counter ; } static public void Main ( ) { int [ ] arr = { 7 , 11 , 22 , 4 , 2 , 1 , 8 , 9 } ; int n = arr . Length ; Console . WriteLine ( LucasSequence ( arr , n ) ) ; } }


"Longest sub | C # implementation of the approach ; Function to return the length of the longest required sub - sequence ; Sort the array ; To store the resultant length ; If array contains only one element then it divides itself ; Every element divides itself ; Count for all numbers which are lesser than a [ i ] ; If a [ i ] % a [ j ] then update the maximum subsequence length , dp [ i ] = Math . max ( dp [ i ] , 1 + dp [ j ] ) where j is in the range [ 0 , i - 1 ] ; If array contains only one element then i = j which doesn 't satisfy the condition ; Driver code"
Solution in C#:

using System ; class GFG { static int find ( int n , int [ ] a ) { Array . Sort ( a ) ; int res = 1 ; int [ ] dp = new int [ n ] ; dp [ 0 ] = 1 ; for ( int i = 1 ; i < n ; i ++ ) { dp [ i ] = 1 ; for ( int j = 0 ; j < i ; j ++ ) { if ( a [ i ] % a [ j ] == 0 ) { dp [ i ] = Math . Max ( dp [ i ] , 1 + dp [ j ] ) ; } } res = Math . Max ( res , dp [ i ] ) ; } return ( res == 1 ) ? - 1 : res ; } public static void Main ( ) { int [ ] a = { 2 , 4 , 6 , 1 , 3 , 11 } ; int n = a . Length ; Console . WriteLine ( find ( n , a ) ) ; } }


"Longest sub | C # implementation of the approach ; Function to return the length of the longest sub - array whose product of elements is 0 ; Driver code"
Solution in C#:

using System ; class GFG { static int longestSubArray ( int [ ] arr , int n ) { bool isZeroPresent = false ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] == 0 ) { isZeroPresent = true ; break ; } } if ( isZeroPresent ) return n ; return 0 ; } public static void Main ( ) { int [ ] arr = { 1 , 2 , 3 , 0 , 1 , 2 , 0 } ; int n = arr . Length ; Console . Write ( longestSubArray ( arr , n ) ) ; } }


"Longest sub | C # implementation of the approach ; Function to return the required length ; To store the filtered numbers ; Filtering the numbers ; If there are no elements to check ; Find the OR of all the filtered elements ; Check if the OR is equal to m ; Driver code"
Solution in C#:

using System ; using System . Collections . Generic ; class GFG { static int findLen ( int [ ] arr , int n , int m ) { List < int > filter = new List < int > ( ) ; for ( int i = 0 ; i < n ; i ++ ) if ( ( arr [ i ] m ) == m ) filter . Add ( arr [ i ] ) ; if ( filter . Count == 0 ) return 0 ; int c_or = filter [ 0 ] ; for ( int i = 1 ; i < filter . Count ; i ++ ) c_or |= filter [ i ] ; if ( c_or == m ) return filter . Count ; return 0 ; } public static void Main ( ) { int [ ] arr = { 7 , 3 , 3 , 1 , 3 } ; int n = arr . Length ; int m = 3 ; Console . Write ( findLen ( arr , n , m ) ) ; } }


"Longest sub | C # implementation to find the length of the longest substring having frequency of each character less than equal to k ; function to find the length of the longest substring having frequency of each character less than equal to k ; hash table to store frequency of each table ; ' start ' index of the current substring ; to store the maximum length ; traverse the string ' str ' ; get the current character as ' ch ' ; increase frequency of ' ch ' in ' freq [ ] ' ; if frequency of ' ch ' becomes more than ' k ' ; update ' maxLen ' ; decrease frequency of each character as they are encountered from the ' start ' index until frequency of ' ch ' is greater than ' k ' ; decrement frequency by '1' ; increment ' start ' ; update maxLen ; required length ; Driver function"
Solution in C#:

using System ; class GfG { public static int SIZE = 26 ; public static int longSubstring ( String str1 , int k ) { int [ ] freq = new int [ SIZE ] ; char [ ] str = str1 . ToCharArray ( ) ; int start = 0 ; int maxLen = 0 ; char ch ; int n = str1 . Length ; for ( int i = 0 ; i < n ; i ++ ) { ch = str [ i ] ; freq [ ch - ' a ' ] ++ ; if ( freq [ ch - ' a ' ] > k ) { if ( maxLen < ( i - start ) ) maxLen = i - start ; while ( freq [ ch - ' a ' ] > k ) { freq [ str [ start ] - ' a ' ] -- ; start ++ ; } } } if ( maxLen < ( n - start ) ) maxLen = n - start ; return maxLen ; } public static void Main ( ) { String str = " babcaag " ; int k = 1 ; Console . Write ( " Length ▁ = ▁ " + longSubstring ( str , k ) ) ; } }


"Longest sub | C # program to find longest subarray of prime numbers ; To store the prime numbers ; Function that find prime numbers till limit ; Find primes using Sieve of Eratosthenes ; Function that finds all prime numbers in given range using Segmented Sieve ; Find the limit ; To store the prime numbers ; Comput all primes less than or equals to sqrt ( high ) using Simple Sieve ; Count the elements in the range [ low , high ] ; Declaring boolean for the range [ low , high ] ; Traverse the prime numbers till limit ; Find the minimum number in [ low . . high ] that is a multiple of prime [ i ] ; Mark the multiples of prime [ i ] in [ low , high ] as true ; Element which are not marked in range are Prime ; Function that finds longest subarray of prime numbers ; If element is Non - prime then updated current_max to 0 ; If element is prime , then update current_max and max_so_far ; Return the count of longest subarray ; Driver code ; Find minimum and maximum element ; Find prime in the range [ min_el , max_el ] ; Function call"
Solution in C#:

using System ; using System . Collections ; using System . Collections . Generic ; class GFG { static HashSet < int > allPrimes = new HashSet < int > ( ) ; static void simpleSieve ( int limit , ref ArrayList prime ) { bool [ ] mark = new bool [ limit + 1 ] ; Array . Fill ( mark , false ) ; for ( int i = 2 ; i <= limit ; ++ i ) { if ( mark [ i ] == false ) { prime . Add ( i ) ; for ( int j = i ; j <= limit ; j += i ) { mark [ j ] = true ; } } } } static void primesInRange ( int low , int high ) { int limit = ( int ) Math . Floor ( Math . Sqrt ( high ) ) + 1 ; ArrayList prime = new ArrayList ( ) ; simpleSieve ( limit , ref prime ) ; int n = high - low + 1 ; bool [ ] mark = new bool [ n + 1 ] ; Array . Fill ( mark , false ) ; for ( int i = 0 ; i < prime . Count ; i ++ ) { int loLim = ( int ) Math . Floor ( ( double ) low / ( int ) prime [ i ] ) ; loLim *= ( int ) prime [ i ] ; if ( loLim < low ) { loLim += ( int ) prime [ i ] ; } if ( loLim == ( int ) prime [ i ] ) { loLim += ( int ) prime [ i ] ; } for ( int j = loLim ; j <= high ; j += ( int ) prime [ i ] ) mark [ j - low ] = true ; } for ( int i = low ; i <= high ; i ++ ) { if ( ! mark [ i - low ] ) { allPrimes . Add ( i ) ; } } } static int maxPrimeSubarray ( int [ ] arr , int n ) { int current_max = 0 ; int max_so_far = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( ! allPrimes . Contains ( arr [ i ] ) ) current_max = 0 ; else { current_max ++ ; max_so_far = Math . Max ( current_max , max_so_far ) ; } } return max_so_far ; } public static void Main ( string [ ] args ) { int [ ] arr = { 1 , 2 , 4 , 3 , 29 , 11 , 7 , 8 , 9 } ; int n = arr . Length ; int max_el = Int32 . MinValue ; int min_el = Int32 . MaxValue ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] < min_el ) { min_el = arr [ i ] ; } if ( arr [ i ] > max_el ) { max_el = arr [ i ] ; } } primesInRange ( min_el , max_el ) ; Console . Write ( maxPrimeSubarray ( arr , n ) ) ; } }


"Longest subarray forming a Geometic Progression ( GP ) | C # program to implement the above approach ; Function to return the length of the longest subarray forming a GP in a sorted array ; Base Case ; Stores the length of GP and the common ratio ; Stores the maximum length of the GP ; Traverse the array ; Check if the common ratio is valid for GP ; If the current common ratio is equal to previous common ratio ; Increment the length of the GP ; Store the max length of GP ; Otherwise ; Update the common ratio ; Update the length of GP ; Store the max length of GP ; Update the length of GP ; Store the max length of GP ; Return the max length of GP ; Driver code ; Given array ; Length of the array ; Function call"
Solution in C#:

using System ; class GFG { static int longestGP ( int [ ] A , int N ) { if ( N < 2 ) return N ; int length = 1 , common_ratio = 1 ; int maxlength = 1 ; for ( int i = 0 ; i < N - 1 ; i ++ ) { if ( A [ i + 1 ] % A [ i ] == 0 ) { if ( A [ i + 1 ] / A [ i ] == common_ratio ) { length = length + 1 ; maxlength = Math . Max ( maxlength , length ) ; } else { common_ratio = A [ i + 1 ] / A [ i ] ; length = 2 ; } } else { maxlength = Math . Max ( maxlength , length ) ; length = 1 ; } } maxlength = Math . Max ( maxlength , length ) ; return maxlength ; } public static void Main ( String [ ] args ) { int [ ] arr = { 1 , 2 , 4 , 7 , 14 , 28 , 56 , 89 } ; int N = arr . Length ; Console . WriteLine ( longestGP ( arr , N ) ) ; } }


"Longest subarray forming an Arithmetic Progression ( AP ) | C # Program to implement the above approach ; Function to return the length of longest subarray forming an AP ; Minimum possible length of required subarray is 2 ; Stores the length of the current subarray ; Stores the common difference of the current AP ; Stores the common difference of the previous AP ; If the common differences are found to be equal ; Continue the previous subarray ; Start a new subarray ; Update the length to store maximum length ; Update the length to store maximum length ; Return the length of the longest subarray ; Driver Code"
Solution in C#:

using System ; public class GFG { static int getMaxLength ( int [ ] arr , int N ) { int res = 2 ; int dist = 2 ; int curradj = ( arr [ 1 ] - arr [ 0 ] ) ; int prevadj = ( arr [ 1 ] - arr [ 0 ] ) ; for ( int i = 2 ; i < N ; i ++ ) { curradj = arr [ i ] - arr [ i - 1 ] ; if ( curradj == prevadj ) { dist ++ ; } else { prevadj = curradj ; res = Math . Max ( res , dist ) ; dist = 2 ; } } res = Math . Max ( res , dist ) ; return res ; } public static void Main ( String [ ] args ) { int [ ] arr = { 10 , 7 , 4 , 6 , 8 , 10 , 11 } ; int N = arr . Length ; Console . Write ( getMaxLength ( arr , N ) ) ; } }


"Longest subarray having count of 1 s one more than count of 0 s | C # implementation to find the length of longest subarray having count of 1 ' s ▁ one ▁ more ▁ than ▁ count ▁ of ▁ 0' s ; function to find the length of longest subarray having count of 1 ' s ▁ one ▁ more ▁ than ▁ count ▁ of ▁ 0' s ; unordered_map ' um ' implemented as hash table ; traverse the given array ; consider '0' as ' - 1' ; when subarray starts form index '0' ; make an entry for ' sum ' if it is not present in ' um ' ; check if ' sum - 1' is present in ' um ' or not ; update maxLength ; required maximum length ; Driver Code"
Solution in C#:

using System ; using System . Collections . Generic ; class GFG { static int lenOfLongSubarr ( int [ ] arr , int n ) { Dictionary < int , int > um = new Dictionary < int , int > ( ) ; int sum = 0 , maxLen = 0 ; for ( int i = 0 ; i < n ; i ++ ) { sum += arr [ i ] == 0 ? - 1 : 1 ; if ( sum == 1 ) maxLen = i + 1 ; else if ( ! um . ContainsKey ( sum ) ) um . Add ( sum , i ) ; if ( um . ContainsKey ( sum - 1 ) ) { if ( maxLen < ( i - um [ sum - 1 ] ) ) maxLen = i - um [ sum - 1 ] ; } } return maxLen ; } public static void Main ( String [ ] args ) { int [ ] arr = { 0 , 1 , 1 , 0 , 0 , 1 } ; int n = arr . Length ; Console . WriteLine ( " Length ▁ = ▁ " + lenOfLongSubarr ( arr , n ) ) ; } }


"Longest subarray having maximum sum | C # implementation to find the length of the longest subarray having maximum sum ; function to find the maximum sum that exists in a subarray ; function to find the length of longest subarray having sum k ; unordered_map ' um ' implemented as hash table ; traverse the given array ; accumulate sum ; when subarray starts from index '0' ; make an entry for ' sum ' if it is not present in ' um ' ; check if ' sum - k ' is present in ' um ' or not ; update maxLength ; required maximum length ; function to find the length of the longest subarray having maximum sum ; Driver Code"
Solution in C#:

using System ; using System . Collections . Generic ; public class GFG { static int maxSubArraySum ( int [ ] arr , int size ) { int max_so_far = arr [ 0 ] ; int curr_max = arr [ 0 ] ; for ( int i = 1 ; i < size ; i ++ ) { curr_max = Math . Max ( arr [ i ] , curr_max + arr [ i ] ) ; max_so_far = Math . Max ( max_so_far , curr_max ) ; } return max_so_far ; } static int lenOfLongSubarrWithGivenSum ( int [ ] arr , int n , int k ) { Dictionary < int , int > um = new Dictionary < int , int > ( ) ; int sum = 0 , maxLen = 0 ; for ( int i = 0 ; i < n ; i ++ ) { sum += arr [ i ] ; if ( sum == k ) maxLen = i + 1 ; if ( um . ContainsKey ( sum ) ) um . Add ( sum , i ) ; if ( um . ContainsKey ( sum - k ) ) { if ( maxLen < ( i - um [ sum - k ] ) ) maxLen = i - um [ sum - k ] ; } } return maxLen ; } static int lenLongSubarrWithMaxSum ( int [ ] arr , int n ) { int maxSum = maxSubArraySum ( arr , n ) ; return lenOfLongSubarrWithGivenSum ( arr , n , maxSum ) ; } public static void Main ( ) { int [ ] arr = { 5 , - 2 , - 1 , 3 , - 4 } ; int n = arr . Length ; Console . WriteLine ( " Length ▁ of ▁ longest ▁ subarray ▁ " + " having ▁ maximum ▁ sum ▁ = ▁ " + lenLongSubarrWithMaxSum ( arr , n ) ) ; } }


"Longest subarray having sum K | Set 2 | C # program for the above approach ; To store the prefix sum array ; Function for searching the lower bound of the subarray ; Iterate until low less than equal to high ; For each mid finding sum of sub array less than or equal to k ; Return the final answer ; Function to find the length of subarray with sum K ; Initialize sum to 0 ; Push the prefix sum of the array [ ] arr in prefix [ ] ; Search r for each i ; Update ans ; Print the length of subarray found in the array ; Driver Code ; Given array [ ] arr ; Given sum K ; Function call"
Solution in C#:

using System ; using System . Collections . Generic ; class GFG { static List < int > v = new List < int > ( ) ; static int bin ( int val , int k , int n ) { int lo = 0 ; int hi = n ; int mid ; int ans = - 1 ; while ( lo <= hi ) { mid = lo + ( hi - lo ) / 2 ; if ( v [ mid ] - val <= k ) { lo = mid + 1 ; ans = mid ; } else hi = mid - 1 ; } return ans ; } static void findSubarraySumK ( int [ ] arr , int N , int K ) { int sum = 0 ; v . Add ( 0 ) ; for ( int i = 0 ; i < N ; i ++ ) { sum += arr [ i ] ; v . Add ( sum ) ; } int ans = 0 , r ; for ( int i = 0 ; i < v . Count ; i ++ ) { r = bin ( v [ i ] , K , N ) ; ans = Math . Max ( ans , r - i ) ; } Console . Write ( ans ) ; } public static void Main ( String [ ] args ) { int [ ] arr = { 6 , 8 , 14 , 9 , 4 , 11 , 10 } ; int N = arr . Length ; int K = 13 ; findSubarraySumK ( arr , N , K ) ; } }


"Longest subarray in which all elements are a factor of K | C # program to implement the above approach ; Function to find the length of the longest subarray in which all elements are a factor of K ; Stores length of the longest subarray in which all elements are a factor of K ; Stores length of the current subarray ; Traverse the array arr [ ] ; If A [ i ] is a factor of K ; Update Len ; Update MaxLen ; If A [ i ] is not a factor of K ; Update Len ; Driver Code"
Solution in C#:

using System ; class GFG { static int find_longest_subarray ( int [ ] A , int N , int K ) { int MaxLen = 0 ; int Len = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( K % A [ i ] == 0 ) { Len ++ ; MaxLen = Math . Max ( MaxLen , Len ) ; } else { Len = 0 ; } } return MaxLen ; } public static void Main ( string [ ] args ) { int [ ] A = { 2 , 8 , 3 , 10 , 6 , 7 , 4 , 9 } ; int N = A . Length ; int K = 60 ; Console . WriteLine ( find_longest_subarray ( A , N , K ) ) ; } }


"Longest subarray in which all elements are smaller than K | C # program for the above approach ; Function to find the length of the longest subarray with all elements smaller than K ; Stores the length of maximum consecutive sequence ; Stores maximum length of subarray ; Iterate through the array ; Check if array element smaller than K ; Store the maximum of length and count ; Reset the counter ; Print the maximum length ; Driver code ; Given array arr [ ] ; Size of the array ; Given K ; Function Call"
Solution in C#:

using System ; class GFG { static void largestSubarray ( int [ ] arr , int N , int K ) { int count = 0 ; int len = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( arr [ i ] < K ) { count += 1 ; } else { len = Math . Max ( len , count ) ; count = 0 ; } } if ( count != 0 ) { len = Math . Max ( len , count ) ; } Console . WriteLine ( len ) ; } static void Main ( ) { int [ ] arr = { 1 , 8 , 3 , 5 , 2 , 2 , 1 , 13 } ; int N = arr . Length ; int K = 6 ; largestSubarray ( arr , N , K ) ; } }


"Longest subarray of an array which is a subsequence in another array | C # program for the above approach ; Function to find the length of the longest subarray in arr1 [ ] which is a subsequence in arr2 [ ] ; Length of the array arr1 [ ] ; Length of the array arr2 [ ] ; Length of the required longest subarray ; Initialize DP [ ] array ; Traverse array arr1 [ ] ; Traverse array arr2 [ ] ; arr1 [ i - 1 ] contributes to the length of the subarray ; Otherwise ; Find the maximum value present in DP [ ] [ ] ; Return the result ; Driver Code ; Function call to find the length of the longest required subarray"
Solution in C#:

using System ; class GFG { private static int LongSubarrSeq ( int [ ] arr1 , int [ ] arr2 ) { int M = arr1 . Length ; int N = arr2 . Length ; int maxL = 0 ; int [ , ] DP = new int [ M + 1 , N + 1 ] ; for ( int i = 1 ; i <= M ; i ++ ) { for ( int j = 1 ; j <= N ; j ++ ) { if ( arr1 [ i - 1 ] == arr2 [ j - 1 ] ) { DP [ i , j ] = 1 + DP [ i - 1 , j - 1 ] ; } else { DP [ i , j ] = DP [ i , j - 1 ] ; } } } for ( int i = 1 ; i <= M ; i ++ ) { for ( int j = 1 ; j <= N ; j ++ ) { maxL = Math . Max ( maxL , DP [ i , j ] ) ; } } return maxL ; } static public void Main ( ) { int [ ] arr1 = { 4 , 2 , 3 , 1 , 5 , 6 } ; int [ ] arr2 = { 3 , 1 , 4 , 6 , 5 , 2 } ; Console . WriteLine ( LongSubarrSeq ( arr1 , arr2 ) ) ; } }


"Longest subarray of non | C # program for the above approach ; Function to find the maximum length of a subarray of 1 s after removing at most one 0 ; Stores the count of consecutive 1 's from left ; Stores the count of consecutive 1 's from right ; Traverse left to right ; If cell is non - empty ; Increase count ; If cell is empty ; Store the count of consecutive 1 's  till (i - 1)-th index ; Traverse from right to left ; Store the count of consecutive 1 s till ( i + 1 ) - th index ; Stores the length of longest subarray ; Store the maximum ; If array a contains only 1 s return n else return ans ; Driver code"
Solution in C#:

using System ; class GFG { public static int longestSubarray ( int [ ] a , int n ) { int [ ] l = new int [ n ] ; int [ ] r = new int [ n ] ; for ( int i = 0 , count = 0 ; i < n ; i ++ ) { if ( a [ i ] == 1 ) count ++ ; else { l [ i ] = count ; count = 0 ; } } for ( int i = n - 1 , count = 0 ; i >= 0 ; i -- ) { if ( a [ i ] == 1 ) count ++ ; else { r [ i ] = count ; count = 0 ; } } int ans = - 1 ; for ( int i = 0 ; i < n ; ++ i ) { if ( a [ i ] == 0 ) ans = Math . Max ( ans , l [ i ] + r [ i ] ) ; } return ans < 0 ? n : ans ; } public static void Main ( ) { int [ ] arr = { 0 , 1 , 1 , 1 , 0 , 1 , 0 , 1 , 1 } ; int n = arr . Length ; Console . Write ( longestSubarray ( arr , n ) ) ; } }


"Longest subarray such that the difference of max and min is at | C # code to find longest subarray with difference between max and min as at - most 1. ; longest constant range length ; first number ; If we see same number ; If we see different number , but same as previous . ; If number is neither same as previous nor as current . ; Driver Code"
Solution in C#:

using System ; class GFG { public static int longestSubarray ( int [ ] input ) { int prev = - 1 ; int current , next ; int prevCount = 0 , currentCount = 1 ; int longest = 1 ; current = input [ 0 ] ; for ( int i = 1 ; i < input . Length ; i ++ ) { next = input [ i ] ; if ( next == current ) { currentCount ++ ; } else if ( next == prev ) { prevCount += currentCount ; prev = current ; current = next ; currentCount = 1 ; } else { longest = Math . Max ( longest , currentCount + prevCount ) ; prev = current ; prevCount = currentCount ; current = next ; currentCount = 1 ; } } return Math . Max ( longest , currentCount + prevCount ) ; } public static void Main ( String [ ] args ) { int [ ] input = { 5 , 5 , 6 , 7 , 6 } ; Console . WriteLine ( longestSubarray ( input ) ) ; } }


"Longest subarray with GCD greater than 1 | C # program of the above approach ; Function to build the Segment Tree from the given array to process range queries in log ( N ) time ; Termination Condition ; Find the mid value ; Left and Right Recursive Call ; Update the Segment Tree Node ; Function to return the GCD of the elements of the Array from index l to index r ; Base Case ; Find the middle range ; Find the GCD and return ; Function to print maximum length of the subarray having GCD > one ; Stores the Segment Tree ; Function call to build the Segment tree from array [ ] arr ; Store maximum length of subarray ; Starting and ending pointer of the current window ; Case where the GCD of the current window is 1 ; Update the maximum length ; Print answer ; Driver Code"
Solution in C#:

using System ; public class GFG { static void build_tree ( int [ ] b , int [ ] seg_tree , int l , int r , int vertex ) { if ( l == r ) { seg_tree [ vertex ] = b [ l ] ; return ; } int mid = ( l + r ) / 2 ; build_tree ( b , seg_tree , l , mid , 2 * vertex ) ; build_tree ( b , seg_tree , mid + 1 , r , 2 * vertex + 1 ) ; seg_tree [ vertex ] = __gcd ( seg_tree [ 2 * vertex ] , seg_tree [ 2 * vertex + 1 ] ) ; } static int __gcd ( int a , int b ) { return b == 0 ? a : __gcd ( b , a % b ) ; } static int range_gcd ( int [ ] seg_tree , int v , int tl , int tr , int l , int r ) { if ( l > r ) return 0 ; if ( l == tl && r == tr ) return seg_tree [ v ] ; int tm = ( tl + tr ) / 2 ; return __gcd ( range_gcd ( seg_tree , 2 * v , tl , tm , l , Math . Min ( tm , r ) ) , range_gcd ( seg_tree , 2 * v + 1 , tm + 1 , tr , Math . Max ( tm + 1 , l ) , r ) ) ; } static void maxSubarrayLen ( int [ ] arr , int n ) { int [ ] seg_tree = new int [ 4 * ( n ) + 1 ] ; build_tree ( arr , seg_tree , 0 , n - 1 , 1 ) ; int maxLen = 0 ; int l = 0 , r = 0 ; while ( r < n && l < n ) { if ( range_gcd ( seg_tree , 1 , 0 , n - 1 , l , r ) == 1 ) { l ++ ; } maxLen = Math . Max ( maxLen , r - l + 1 ) ; r ++ ; } Console . Write ( maxLen ) ; } public static void Main ( String [ ] args ) { int [ ] arr = { 410 , 52 , 51 , 180 , 222 , 33 , 33 } ; int N = arr . Length ; maxSubarrayLen ( arr , N ) ; } }


"Longest subarray with all elements same | C # program to find largest subarray with all equal elements . ; Function to find largest sub array with all equal elements . ; Traverse the array ; If element is same as previous increment temp value ; Return the required answer ; Driver code ; Function call"
Solution in C#:

using System ; class GFG { static int subarray ( int [ ] arr , int n ) { int ans = 1 , temp = 1 ; for ( int i = 1 ; i < n ; i ++ ) { if ( arr [ i ] == arr [ i - 1 ] ) { ++ temp ; } else { ans = Math . Max ( ans , temp ) ; temp = 1 ; } } ans = Math . Max ( ans , temp ) ; return ans ; } public static void Main ( ) { int [ ] arr = { 2 , 2 , 1 , 1 , 2 , 2 , 2 , 3 , 3 } ; int n = arr . Length ; Console . Write ( subarray ( arr , n ) ) ; } }


"Longest subarray with all even or all odd elements | C # implementation for the above approach ; Function to calculate longest subString with odd or even elements ; Initializing dp ; Initializing dp with 1 ; ans will store the readonly answer ; Traversing the array from index 1 to N - 1 ; Checking both current and previous element is even or odd ; Updating dp with ( previous dp value ) + 1 ; Storing max element so far to ans ; Returning the readonly answer ; Driver code ; Input ; Function call"
Solution in C#:

using System ; public class GFG { static int longestOddEvenSubarray ( int [ ] A , int N ) { int dp ; dp = 1 ; int ans = 1 ; for ( int i = 1 ; i < N ; i ++ ) { if ( ( A [ i ] % 2 == 0 && A [ i - 1 ] % 2 == 0 ) || ( A [ i ] % 2 != 0 && A [ i - 1 ] % 2 != 0 ) ) { dp = dp + 1 ; ans = Math . Max ( ans , dp ) ; } else dp = 1 ; } return ans ; } public static void Main ( String [ ] args ) { int [ ] A = { 2 , 5 , 7 , 2 , 4 , 6 , 8 , 3 } ; int N = A . Length ; Console . Write ( longestOddEvenSubarray ( A , N ) ) ; } }


"Longest subarray with all even or all odd elements | C # program for the above approach ; Function to calculate longest substring with odd or even elements ; Initializing dp [ ] ; Initializing dp [ 0 ] with 1 ; ans will store the final answer ; Traversing the array from index 1 to N - 1 ; Checking both current and previous element is even or odd ; Updating dp [ i ] with dp [ i - 1 ] + 1 ; Storing max element to ans ; Returning the final answer ; Driver Code ; Input ; Function call"
Solution in C#:

using System ; class GFG { static int LongestOddEvenSubarray ( int [ ] A , int N ) { int [ ] dp = new int [ N ] ; dp [ 0 ] = 1 ; int ans = 1 ; for ( int i = 1 ; i < N ; i ++ ) { if ( ( A [ i ] % 2 == 0 && A [ i - 1 ] % 2 == 0 ) || ( A [ i ] % 2 != 0 && A [ i - 1 ] % 2 != 0 ) ) { dp [ i ] = dp [ i - 1 ] + 1 ; } else dp [ i ] = 1 ; } for ( int i = 0 ; i < N ; i ++ ) ans = Math . Max ( ans , dp [ i ] ) ; return ans ; } public static void Main ( ) { int [ ] A = { 2 , 5 , 7 , 2 , 4 , 6 , 8 , 3 } ; int N = A . Length ; Console . Write ( LongestOddEvenSubarray ( A , N ) ) ; } }


"Longest subarray with difference exactly K between any two distinct values | C # implementation to find the longest subarray consisting of only two values with difference K ; Function to return the length of the longest sub - array ; Initialize set ; Store 1 st element of sub - array into set ; Check absolute difference between two elements ; If the new element is not present in the set ; If the set contains two elements ; Otherwise ; Update the maximum length ; Remove the set elements ; Driver Code"
Solution in C#:

using System ; using System . Collections . Generic ; class GFG { static int longestSubarray ( int [ ] arr , int n , int k ) { int i , j , Max = 1 ; HashSet < int > s = new HashSet < int > ( ) ; for ( i = 0 ; i < n - 1 ; i ++ ) { s . Add ( arr [ i ] ) ; for ( j = i + 1 ; j < n ; j ++ ) { if ( Math . Abs ( arr [ i ] - arr [ j ] ) == 0 || Math . Abs ( arr [ i ] - arr [ j ] ) == k ) { if ( ! s . Contains ( arr [ j ] ) ) { if ( s . Count == 2 ) break ; else s . Add ( arr [ j ] ) ; } } else break ; } if ( s . Count == 2 ) { Max = Math . Max ( Max , j - i ) ; s . Clear ( ) ; } else s . Clear ( ) ; } return Max ; } public static void Main ( String [ ] args ) { int [ ] arr = { 1 , 0 , 2 , 2 , 5 , 5 , 5 } ; int N = arr . Length ; int K = 1 ; int length = longestSubarray ( arr , N , K ) ; if ( length == 1 ) Console . Write ( - 1 ) ; else Console . Write ( length ) ; } }


"Longest subarray with elements divisible by k | C # program of above approach ; function to find longest subarray ; this will contain length of longest subarray found ; Driver code"
Solution in C#:

using System ; class GFG { static int longestsubarray ( int [ ] arr , int n , int k ) { int current_count = 0 ; int max_count = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] % k == 0 ) current_count ++ ; else current_count = 0 ; max_count = Math . Max ( current_count , max_count ) ; } return max_count ; } public static void Main ( ) { int [ ] arr = { 2 , 5 , 11 , 32 , 64 , 88 } ; int n = arr . Length ; int k = 8 ; Console . Write ( longestsubarray ( arr , n , k ) ) ; } }


"Longest subarray with elements having equal modulo K | C # implementation of above approach ; function to find longest sub - array whose elements gives same remainder when divided with K ; Iterate in the array ; check if array element greater then X or not ; Driver code"
Solution in C#:

using System ; class GFG { static int LongestSubarray ( int [ ] arr , int n , int k ) { int count = 1 ; int max_length = 1 ; int prev_mod = arr [ 0 ] % k ; for ( int i = 1 ; i < n ; i ++ ) { int curr_mod = arr [ i ] % k ; if ( curr_mod == prev_mod ) { count ++ ; } else { max_length = Math . Max ( max_length , count ) ; count = 1 ; prev_mod = curr_mod ; } } return Math . Max ( max_length , count ) ; } public static void Main ( ) { int [ ] arr = { 4 , 9 , 7 , 18 , 29 , 11 } ; int n = arr . Length ; int k = 11 ; Console . Write ( LongestSubarray ( arr , n , k ) ) ; } }


"Longest subarray with odd product | C # program to find the longest subarray with odd product ; Function to return length of longest subarray with odd product ; If even element is encountered ; Update maximum ; Driver Code"
Solution in C#:

using System ; class GFG { static int Maxlen ( int [ ] arr , int n ) { int ans = 0 ; int count = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] % 2 == 0 ) count = 0 ; else count ++ ; ans = Math . Max ( ans , count ) ; } return ans ; } public static void Main ( ) { int [ ] arr = { 1 , 7 , 2 } ; int n = arr . Length ; Console . WriteLine ( Maxlen ( arr , n ) ) ; } }


"Longest subarray with sum not divisible by X | C # program to implement the above approach ; Function to print the longest subarray with sum of elements not divisible by X ; Pref [ ] stores the prefix sum Suff [ ] stores the suffix sum ; If array element is divisibile by x ; Increase count ; If all the array elements are divisible by x ; No subarray possible ; Reverse v to calculate the suffix sum ; Calculate the suffix sum ; Reverse to original form ; Reverse the suffix sum array ; Calculate the prefix sum ; Stores the starting index of required subarray ; Stores the ending index of required subarray ; If suffix sum till i - th index is not divisible by x ; Update the answer ; If prefix sum till i - th index is not divisible by x ; Update the answer ; Print the longest subarray ; Driver Code"
Solution in C#:

 using System ; using System . Collections . Generic ; class GFG { static void max_length ( int N , int x , int [ ] v ) { int i , a ; List < int > preff = new List < int > ( ) ; List < int > suff = new List < int > ( ) ; int ct = 0 ; for ( i = 0 ; i < N ; i ++ ) { a = v [ i ] ; if ( a % x == 0 ) { ct += 1 ; } } if ( ct == N ) { Console . Write ( - 1 + "
 " ) ; return ; } v = reverse ( v ) ; suff . Add ( v [ 0 ] ) ; for ( i = 1 ; i < N ; i ++ ) { suff . Add ( v [ i ] + suff [ i - 1 ] ) ; } v = reverse ( v ) ; suff . Reverse ( ) ; preff . Add ( v [ 0 ] ) ; for ( i = 1 ; i < N ; i ++ ) { preff . Add ( v [ i ] + preff [ i - 1 ] ) ; } int ans = 0 ; int lp = 0 ; int rp = N - 1 ; for ( i = 0 ; i < N ; i ++ ) { if ( suff [ i ] % x != 0 && ( ans < ( N - 1 ) ) ) { lp = i ; rp = N - 1 ; ans = Math . Max ( ans , N - i ) ; } if ( preff [ i ] % x != 0 && ( ans < ( i + 1 ) ) ) { lp = 0 ; rp = i ; ans = Math . Max ( ans , i + 1 ) ; } } for ( i = lp ; i <= rp ; i ++ ) { Console . Write ( v [ i ] + " ▁ " ) ; } } static int [ ] reverse ( int [ ] a ) { int i , n = a . Length , t ; for ( i = 0 ; i < n / 2 ; i ++ ) { t = a [ i ] ; a [ i ] = a [ n - i - 1 ] ; a [ n - i - 1 ] = t ; } return a ; } public static void Main ( String [ ] args ) { int x = 3 ; int [ ] v = { 1 , 3 , 2 , 6 } ; int N = v . Length ; max_length ( N , x , v ) ; } }


"Longest subsequence forming an Arithmetic Progression ( AP ) | C # program for the above approach ; Function that finds the longest arithmetic subsequence having the same absolute difference ; Stores the length of sequences having same difference ; Stores the resultant length ; Iterate over the array ; Update length of subsequence ; Return res ; Driver Code ; Given array arr [ ] ; Function call"
Solution in C#:

using System ; using System . Collections . Generic ; class GFG { static int lenghtOfLongestAP ( int [ ] A , int n ) { Dictionary < int , Dictionary < int , int > > dp = new Dictionary < int , Dictionary < int , int > > ( ) ; int res = 2 ; for ( int i = 0 ; i < n ; ++ i ) { for ( int j = i + 1 ; j < n ; ++ j ) { int d = A [ j ] - A [ i ] ; if ( dp . ContainsKey ( d ) ) { if ( dp [ d ] . ContainsKey ( i ) ) { dp [ d ] [ j ] = dp [ d ] [ i ] + 1 ; } else { dp [ d ] [ j ] = 2 ; } } else { dp [ d ] = new Dictionary < int , int > ( ) ; dp [ d ] [ j ] = 2 ; } res = Math . Max ( res , dp [ d ] [ j ] ) ; } } return res ; } public static void Main ( string [ ] args ) { int [ ] arr = { 20 , 1 , 15 , 3 , 10 , 5 , 8 } ; int N = arr . Length ; Console . Write ( lenghtOfLongestAP ( arr , N ) ) ; } }


"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"
Solution in C#:

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 ) ) ; } }


"Longest subsequence having maximum GCD between any pair of distinct elements | C # program for the above approach ; Recursive function to return gcd of a and b ; Function to find GCD of pair with maximum GCD ; Stores maximum element of [ ] arr ; Find the maximum element ; Maintain a count array ; Store the frequency of [ ] arr ; Stores the multiples of a number ; Iterate over the range [ MAX , 1 ] ; Iterate from current potential GCD till it is less than MAX ; A multiple found ; Increment potential GCD by itself io check i , 2 i , 3 i ... ; If 2 multiples found max GCD found ; Function to find longest subsequence such that GCD of any two distinct integers is maximum ; Base Cases ; Compare current GCD to the maximum GCD ; If true increment and move the pointer ; Return max of either subsequences ; Driver Code ; Sorted array ; Function call to calculate GCD of pair with maximum GCD ; Print the result"
Solution in C#:

using System ; class GFG { static int __gcd ( int a , int b ) { return b == 0 ? a : __gcd ( b , a % b ) ; } static int findMaxGCD ( int [ ] arr , int N ) { int high = 0 ; for ( int i = 0 ; i < N ; i ++ ) { high = Math . Max ( high , arr [ i ] ) ; } int [ ] count = new int [ high + 1 ] ; for ( int i = 0 ; i < N ; i ++ ) { count [ arr [ i ] ] += 1 ; } int counter = 0 ; for ( int i = high ; i > 0 ; i -- ) { int j = i ; while ( j <= high ) { if ( count [ j ] > 0 ) counter += count [ j ] ; j += i ; if ( counter == 2 ) return i ; } counter = 0 ; } return 0 ; } static int maxlen ( int i , int j , int [ ] arr , int [ ] arr1 , int N , int maxgcd ) { int a = 1 ; if ( i >= N j >= N ) return 0 ; if ( __gcd ( arr [ i ] , arr1 [ j ] ) == maxgcd && arr [ i ] != arr1 [ j ] ) { a = Math . Max ( a , 1 + maxlen ( i , j + 1 , arr , arr1 , N , maxgcd ) ) ; return a ; } return Math . Max ( maxlen ( i + 1 , j , arr , arr1 , N , maxgcd ) , maxlen ( i , j + 1 , arr , arr1 , N , maxgcd ) ) ; } public static void Main ( String [ ] args ) { int [ ] arr = { 1 , 2 , 8 , 5 , 6 } ; int [ ] arr1 = { 1 , 2 , 8 , 5 , 6 } ; int n = arr . Length ; Array . Sort ( arr ) ; int maxgcd = findMaxGCD ( arr , n ) ; Console . Write ( maxlen ( 0 , 0 , arr , arr1 , n , maxgcd ) ) ; } }


"Longest subsequence having maximum sum | C # program to implement the above approach ; Function to find the longest subsequence from the given array with maximum sum ; Stores the largest element of the array ; If Max is less than 0 ; Print the largest element of the array ; Traverse the array ; If arr [ i ] is greater than or equal to 0 ; Print elements of the subsequence ; Driver Code"
Solution in C#:

using System ; class GFG { static void longestSubWithMaxSum ( int [ ] arr , int N ) { int Max = arr [ 0 ] ; for ( int i = 1 ; i < N ; i ++ ) { if ( Max < arr [ i ] ) Max = arr [ i ] ; } if ( Max < 0 ) { Console . Write ( Max ) ; return ; } for ( int i = 0 ; i < N ; i ++ ) { if ( arr [ i ] >= 0 ) { Console . Write ( arr [ i ] + " ▁ " ) ; } } } public static void Main ( String [ ] args ) { int [ ] arr = { 1 , 2 , - 4 , - 2 , 3 , 0 } ; int N = arr . Length ; longestSubWithMaxSum ( arr , N ) ; } }


"Longest subsequence of a number having same left and right rotation | C # Program to implement the above approach ; Function to find the longest subsequence having equal left and right rotation ; Length of the String ; Iterate for all possible combinations of a two - digit numbers ; Check for alternate occurrence of current combination ; Increment the current value ; Increment the current value ; If alternating sequence is obtained of odd length ; Reduce to even length ; Update answer to store the maximum ; Return the answer ; Driver Code"
Solution in C#:

using System ; class GFG { static int findAltSubSeq ( String s ) { int n = s . Length , ans = int . MinValue ; for ( int i = 0 ; i < 10 ; i ++ ) { for ( int j = 0 ; j < 10 ; j ++ ) { int cur = 0 , f = 0 ; for ( int k = 0 ; k < n ; k ++ ) { if ( f == 0 && s [ k ] - '0' == i ) { f = 1 ; cur ++ ; } else if ( f == 1 && s [ k ] - '0' == j ) { f = 0 ; cur ++ ; } } if ( i != j && cur % 2 == 1 ) cur -- ; ans = Math . Max ( cur , ans ) ; } } return ans ; } public static void Main ( String [ ] args ) { String s = "100210601" ; Console . Write ( findAltSubSeq ( s ) ) ; } }


"Longest subsequence of the form 0 * 1 * 0 * in a binary string | C # program to find longest subsequence of the form 0 * 1 * 0 * in a binary string ; Returns length of the longest subsequence of the form 0 * 1 * 0 * ; Precomputing values in three arrays pre_count_0 [ i ] is going to store count of 0 s in prefix str [ 0. . i - 1 ] pre_count_1 [ i ] is going to store count of 1 s in prefix str [ 0. . i - 1 ] post_count_0 [ i ] is going to store count of 0 s in suffix str [ i - 1. . n - 1 ] ; string is made up of all 0 s or all 1 s ; Compute result using precomputed values ; Driver code"
Solution in C#:

using System ; class GFG { public static int longestSubseq ( String s ) { int n = s . Length ; int [ ] pre_count_0 = new int [ n + 2 ] ; int [ ] pre_count_1 = new int [ n + 1 ] ; int [ ] post_count_0 = new int [ n + 2 ] ; pre_count_0 [ 0 ] = 0 ; post_count_0 [ n + 1 ] = 0 ; pre_count_1 [ 0 ] = 0 ; for ( int j = 1 ; j <= n ; j ++ ) { pre_count_0 [ j ] = pre_count_0 [ j - 1 ] ; pre_count_1 [ j ] = pre_count_1 [ j - 1 ] ; post_count_0 [ n - j + 1 ] = post_count_0 [ n - j + 2 ] ; if ( s [ j - 1 ] == '0' ) pre_count_0 [ j ] ++ ; else pre_count_1 [ j ] ++ ; if ( s [ n - j ] == '0' ) post_count_0 [ n - j + 1 ] ++ ; } if ( pre_count_0 [ n ] == n pre_count_0 [ n ] == 0 ) return n ; int ans = 0 ; for ( int i = 1 ; i <= n ; i ++ ) for ( int j = i ; j <= n ; j ++ ) ans = Math . Max ( pre_count_0 [ i - 1 ] + pre_count_1 [ j ] - pre_count_1 [ i - 1 ] + post_count_0 [ j + 1 ] , ans ) ; return ans ; } public static void Main ( String [ ] args ) { String s = "000011100000" ; Console . WriteLine ( longestSubseq ( s ) ) ; } }


"Longest subsequence such that adjacent elements have at least one common digit | C # program to find maximum length subsequence such that adjacent elements have at least one common digit ; Returns length of maximum length subsequence ; To store the length of the maximum length subsequence ; To store current element arr [ i ] ; To store the length of the sub - sequence ending at index i and having common digit d ; To store digits present in current element ; To store length of maximum length subsequence ending at index i ; For first element maximum length is 1 for each digit ; Find digits of each element , then find length of subsequence for each digit and then find local maximum ; Find digits in current element ; For each digit present find length of subsequence and find local maximum ; Update value of dp [ i , d ] for each digit present in current element to local maximum found . ; Update maximum length with local maximum ; Driver code"
Solution in C#:

using System ; class GFG { static int findSubsequence ( int [ ] arr , int n ) { int len = 1 ; int tmp ; int i , j , d ; int [ , ] dp = new int [ n , 10 ] ; int [ ] cnt = new int [ 10 ] ; int locMax ; tmp = arr [ 0 ] ; while ( tmp > 0 ) { dp [ 0 , tmp % 10 ] = 1 ; tmp /= 10 ; } for ( i = 1 ; i < n ; i ++ ) { tmp = arr [ i ] ; locMax = 1 ; for ( int x = 0 ; x < 10 ; x ++ ) cnt [ x ] = 0 ; while ( tmp > 0 ) { cnt [ tmp % 10 ] = 1 ; tmp /= 10 ; } for ( d = 0 ; d <= 9 ; d ++ ) { if ( cnt [ d ] > 0 ) { dp [ i , d ] = 1 ; for ( j = 0 ; j < i ; j ++ ) { dp [ i , d ] = Math . Max ( dp [ i , d ] , dp [ j , d ] + 1 ) ; locMax = Math . Max ( dp [ i , d ] , locMax ) ; } } } for ( d = 0 ; d <= 9 ; d ++ ) { if ( cnt [ d ] > 0 ) { dp [ i , d ] = locMax ; } } len = Math . Max ( len , locMax ) ; } return len ; } public static void Main ( ) { int [ ] arr = { 1 , 12 , 44 , 29 , 33 , 96 , 89 } ; int n = arr . Length ; Console . WriteLine ( findSubsequence ( arr , n ) ) ; } }


"Longest subsequence such that difference between adjacents is one | C # program to find the longest subsequence such that the difference between adjacent elements of the subsequence is one . ; Function to find the length of longest subsequence ; Initialize the dp [ ] array with 1 as a single element will be of 1 length ; Start traversing the given array ; Compare with all the previous elements ; If the element is consecutive then consider this subsequence and update dp [ i ] if required . ; Longest length will be the maximum value of dp array . ; Driver code ; Longest subsequence with one difference is { 1 , 2 , 3 , 4 , 3 , 2 }"
Solution in C#:

using System ; class GFG { static int longestSubseqWithDiffOne ( int [ ] arr , int n ) { int [ ] dp = new int [ n ] ; for ( int i = 0 ; i < n ; i ++ ) dp [ i ] = 1 ; for ( int i = 1 ; i < n ; i ++ ) { for ( int j = 0 ; j < i ; j ++ ) { if ( ( arr [ i ] == arr [ j ] + 1 ) || ( arr [ i ] == arr [ j ] - 1 ) ) dp [ i ] = Math . Max ( dp [ i ] , dp [ j ] + 1 ) ; } } int result = 1 ; for ( int i = 0 ; i < n ; i ++ ) if ( result < dp [ i ] ) result = dp [ i ] ; return result ; } public static void Main ( ) { int [ ] arr = { 1 , 2 , 3 , 4 , 5 , 3 , 2 } ; int n = arr . Length ; Console . Write ( longestSubseqWithDiffOne ( arr , n ) ) ; } }


"Longest subsequence such that difference between adjacents is one | Set 2 | C # implementation to find longest subsequence such that difference between adjacents is one ; function to find longest subsequence such that difference between adjacents is one ; hash table to map the array element with the length of the longest subsequence of which it is a part of and is the last element of that subsequence ; to store the longest length subsequence ; traverse the array elements ; initialize current length for element arr [ i ] as 0 ; if ' arr [ i ] -1' is in ' um ' and its length of subsequence is greater than ' len ' ; if ' arr [ i ] + 1' is in ' um ' and its length of subsequence is greater than ' len ' ; update arr [ i ] subsequence length in ' um ' ; update longest length ; required longest length subsequence ; Driver program to test above"
Solution in C#:

using System ; using System . Collections . Generic ; class GFG { static int longLenSub ( int [ ] arr , int n ) { Dictionary < int , int > um = new Dictionary < int , int > ( ) ; int longLen = 0 ; for ( int i = 0 ; i < n ; i ++ ) { int len = 0 ; if ( um . ContainsKey ( arr [ i ] - 1 ) && len < um [ arr [ i ] - 1 ] ) len = um [ arr [ i ] - 1 ] ; if ( um . ContainsKey ( arr [ i ] + 1 ) && len < um [ arr [ i ] + 1 ] ) len = um [ arr [ i ] + 1 ] ; um [ arr [ i ] ] = len + 1 ; if ( longLen < um [ arr [ i ] ] ) longLen = um [ arr [ i ] ] ; } return longLen ; } static void Main ( ) { int [ ] arr = { 1 , 2 , 3 , 4 , 5 , 3 , 2 } ; int n = arr . Length ; Console . Write ( " Longest ▁ length ▁ subsequence ▁ = ▁ " + longLenSub ( arr , n ) ) ; } }


"Longest subsequence where every character appears at | C # program to Find longest subsequence where every character appears at - least k times ; Count frequencies of all characters ; Traverse given string again and print all those characters whose frequency is more than or equal to k . ; Driver code"
Solution in C#:

using System ; public class GFG { static readonly int MAX_CHARS = 26 ; static void longestSubseqWithK ( String str , int k ) { int n = str . Length ; int [ ] freq = new int [ MAX_CHARS ] ; for ( int i = 0 ; i < n ; i ++ ) { freq [ str [ i ] - ' a ' ] ++ ; } for ( int i = 0 ; i < n ; i ++ ) { if ( freq [ str [ i ] - ' a ' ] >= k ) { Console . Write ( str [ i ] ) ; } } } static public void Main ( ) { String str = " geeksforgeeks " ; int k = 2 ; longestSubseqWithK ( str , k ) ; } }


"Longest subsequence whose average is less than K | C # program to perform Q queries to find longest subsequence whose average is less than K ; Function to print the length for evey query ; sort array of N elements ; Array to store average from left ; Sort array of average ; number of queries ; print answer to every query using binary search ; Driver Code ; 4 queries"
Solution in C#:

using System ; class GFG { static void longestSubsequence ( int [ ] a , int n , int [ ] q , int m ) { Array . Sort ( a ) ; int sum = 0 ; int [ ] b = new int [ n ] ; for ( int i = 0 ; i < n ; i ++ ) { sum += a [ i ] ; double av = ( double ) ( sum ) / ( double ) ( i + 1 ) ; b [ i ] = ( ( int ) ( av + 1 ) ) ; } Array . Sort ( b ) ; for ( int i = 0 ; i < m ; i ++ ) { int k = q [ i ] ; int longest = upperBound ( b , 0 , n , k ) ; Console . WriteLine ( " Answer ▁ to ▁ Query " + ( i + 1 ) + " : ▁ " + longest ) ; } } private static int upperBound ( int [ ] a , int low , int high , int element ) { while ( low < high ) { int middle = low + ( high - low ) / 2 ; if ( a [ middle ] > element ) high = middle ; else low = middle + 1 ; } return low ; } static public void Main ( ) { int [ ] a = { 1 , 3 , 2 , 5 , 4 } ; int n = a . Length ; int [ ] q = { 4 , 2 , 1 , 5 } ; int m = q . Length ; longestSubsequence ( a , n , q , m ) ; } }


"Longest subsequence whose sum is divisible by a given number | C # implementation of the approach ; To store the states of DP ; Function to return the length of the longest subsequence whose sum is divisible by m ; Base case ; If the state has been solved before return the value of the state ; Setting the state as solved ; Recurrence relation ; Driver code"
Solution in C#:

using System ; class GFG { static int maxN = 20 ; static int maxM = 64 ; static int [ , ] dp = new int [ maxN , maxM ] ; static Boolean [ , ] v = new Boolean [ maxN , maxM ] ; static int findLen ( int [ ] arr , int i , int curr , int n , int m ) { if ( i == n ) { if ( curr == 0 ) return 0 ; else return - 1 ; } if ( v [ i , curr ] ) return dp [ i , curr ] ; v [ i , curr ] = true ; int l = findLen ( arr , i + 1 , curr , n , m ) ; int r = findLen ( arr , i + 1 , ( curr + arr [ i ] ) % m , n , m ) ; dp [ i , curr ] = l ; if ( r != - 1 ) dp [ i , curr ] = Math . Max ( dp [ i , curr ] , r + 1 ) ; return dp [ i , curr ] ; } public static void Main ( String [ ] args ) { int [ ] arr = { 3 , 2 , 2 , 1 } ; int n = arr . Length ; int m = 3 ; Console . WriteLine ( findLen ( arr , 0 , 0 , n , m ) ) ; } }


"Longest subsequence with a given AND value | C # implementation of the approach ; To store the states of DP ; Function to return the required length ; Base case ; If the state has been solved before return the value of the state ; Setting the state as solved ; Recurrence relation ; Driver code"
Solution in C#:

using System ; class GFG { static int maxN = 300 ; static int maxM = 300 ; static int [ , ] dp = new int [ maxN , maxM ] ; static bool [ , ] v = new bool [ maxN , maxM ] ; static int findLen ( int [ ] arr , int i , int curr , int n , int m ) { if ( i == n ) { if ( curr == m ) return 0 ; else return - 1 ; } if ( v [ i , curr ] ) return dp [ i , curr ] ; v [ i , curr ] = true ; int l = findLen ( arr , i + 1 , curr , n , m ) ; int r = findLen ( arr , i + 1 , curr & arr [ i ] , n , m ) ; dp [ i , curr ] = l ; if ( r != - 1 ) dp [ i , curr ] = Math . Max ( dp [ i , curr ] , r + 1 ) ; return dp [ i , curr ] ; } public static void Main ( String [ ] args ) { int [ ] arr = { 3 , 7 , 2 , 3 } ; int n = arr . Length ; int m = 3 ; int ans = findLen ( arr , 0 , ( ( 1 << 8 ) - 1 ) , n , m ) ; if ( ans == - 1 ) Console . WriteLine ( 0 ) ; else Console . WriteLine ( ans ) ; } }


"Longest subsequence with a given AND value | O ( N ) | C # implementation of the approach ; Function to return the required length ; To store the filtered numbers ; Filtering the numbers ; If there are no elements to check ; Find the AND of all the filtered elements ; Check if the AND is equal to m ; Driver code"
Solution in C#:

using System ; using System . Collections . Generic ; class GFG { static int findLen ( int [ ] arr , int n , int m ) { List < int > filter = new List < int > ( ) ; for ( int i = 0 ; i < n ; i ++ ) if ( ( arr [ i ] & m ) == m ) filter . Add ( arr [ i ] ) ; if ( filter . Count == 0 ) return 0 ; int c_and = filter [ 0 ] ; for ( int i = 1 ; i < filter . Count ; i ++ ) c_and &= filter [ i ] ; if ( c_and == m ) return filter . Count ; return 0 ; } public static void Main ( String [ ] args ) { int [ ] arr = { 7 , 3 , 3 , 1 , 3 } ; int n = arr . Length ; int m = 3 ; Console . WriteLine ( findLen ( arr , n , m ) ) ; } }


"Longest subsequence with a given OR value : Dynamic Programming Approach | C # implementation of the approach ; To store the states of DP ; Function to return the required length ; Base case ; If the state has been solved before return the value of the state ; Setting the state as solved ; Recurrence relation ; Driver code"
Solution in C#:

using System ; class GFG { static int maxN = 20 ; static int maxM = 64 ; static int [ , ] dp = new int [ maxN , maxM ] ; static bool [ , ] v = new bool [ maxN , maxM ] ; static int findLen ( int [ ] arr , int i , int curr , int n , int m ) { if ( i == n ) { if ( curr == m ) return 0 ; else return - 1 ; } if ( v [ i , curr ] ) return dp [ i , curr ] ; v [ i , curr ] = true ; int l = findLen ( arr , i + 1 , curr , n , m ) ; int r = findLen ( arr , i + 1 , curr arr [ i ] , n , m ) ; dp [ i , curr ] = l ; if ( r != - 1 ) dp [ i , curr ] = Math . Max ( dp [ i , curr ] , r + 1 ) ; return dp [ i , curr ] ; } public static void Main ( String [ ] args ) { int [ ] arr = { 3 , 7 , 2 , 3 } ; int n = arr . Length ; int m = 3 ; int ans = findLen ( arr , 0 , 0 , n , m ) ; if ( ans == - 1 ) Console . WriteLine ( 0 ) ; else Console . WriteLine ( ans ) ; } }


"Longest subsequence with consecutive English alphabets | C # program for the above approach ; Function to find the length of subsequence starting with character ch ; Length of the string ; Stores the maximum length ; Traverse the given string ; If s [ i ] is required character ch ; Increment ans by 1 ; Increment character ch ; Return the current maximum length with character ch ; Function to find the maximum length of subsequence of consecutive characters ; Stores the maximum length of consecutive characters ; Update ans ; Return the maximum length of subsequence ; Driver Code ; Input ; Function Call"
Solution in C#:

using System ; using System . Collections . Generic ; class GFG { static int findSubsequence ( string S , char ch ) { int N = S . Length ; int ans = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( S [ i ] == ch ) { ans ++ ; ch ++ ; } } return ans ; } static int findMaxSubsequence ( string S ) { int ans = 0 ; for ( char ch = ' a ' ; ch <= ' z ' ; ch ++ ) { ans = Math . Max ( ans , findSubsequence ( S , ch ) ) ; } return ans ; } public static void Main ( ) { string S = " abcabefghijk " ; Console . Write ( findMaxSubsequence ( S ) ) ; } }


"Longest subsequence with different adjacent characters | C # program for the above approach ; Function to find the longest subsequence with different adjacent character ; Length of the String s ; Previously picked character ; If the current character is different from the previous then include this character and update previous character ; Driver Code ; Function call"
Solution in C#:

using System ; class GFG { static int longestSubsequence ( String s ) { int n = s . Length ; int answer = 0 ; char prev = ' - ' ; for ( int i = 0 ; i < n ; i ++ ) { if ( prev != s [ i ] ) { prev = s [ i ] ; answer ++ ; } } return answer ; } public static void Main ( String [ ] args ) { String str = " ababa " ; Console . Write ( longestSubsequence ( str ) ) ; } }


"Longest subsequence with different adjacent characters | C # program for the above approach ; dp table ; A recursive function to find the update the [ , ] dp table ; If we reach end of the String ; If subproblem has been computed ; Initialise variable to find the maximum length ; Choose the current character ; Omit the current character ; Return the store answer to the current subproblem ; Function to find the longest Subsequence with different adjacent character ; Length of the String s ; Initialise the memoisation table ; Return the readonly ans after every recursive call ; Driver Code ; Function call"
Solution in C#:

using System ; public class GFG { static int [ , ] dp = new int [ 100005 , 27 ] ; static int calculate ( int pos , int prev , String s ) { if ( pos == s . Length ) { return 0 ; } if ( dp [ pos , prev ] != - 1 ) return dp [ pos , prev ] ; int val = 0 ; if ( s [ pos ] - ' a ' + 1 != prev ) { val = Math . Max ( val , 1 + calculate ( pos + 1 , s [ pos ] - ' a ' + 1 , s ) ) ; } val = Math . Max ( val , calculate ( pos + 1 , prev , s ) ) ; return dp [ pos , prev ] = val ; } static int longestSubsequence ( String s ) { int n = s . Length ; for ( int i = 0 ; i < 100005 ; i ++ ) { for ( int j = 0 ; j < 27 ; j ++ ) { dp [ i , j ] = - 1 ; } } return calculate ( 0 , 0 , s ) ; } public static void Main ( String [ ] args ) { String str = " ababa " ; Console . Write ( longestSubsequence ( str ) ) ; } }


"Longest subsequence with non negative prefix sum at each position | C # program for the above approach ; Function to find the length of the longest subsequence with non negative prefix sum at each position ; Stores the maximum sum possible if we include j elements till the position i ; Initialize dp array with - 1 ; Maximum subsequence sum by including no elements till position ' i ' ; Maximum subsequence sum by including first element at first position ; Iterate over all the remaining positions ; If the current element is excluded ; If current element is included and if total sum is positive or not ; Select the maximum j by which a non negative prefix sum subsequence can be obtained ; Print the answer ; Driver code"
Solution in C#:

using System ; class GFG { static void longestSubsequence ( int [ ] arr , int N ) { int [ , ] dp = new int [ N , N + 1 ] ; for ( int i = 0 ; i < N ; ++ i ) { for ( int j = 0 ; j < N + 1 ; ++ j ) { dp [ i , j ] = - 1 ; } } for ( int i = 0 ; i < N ; ++ i ) { dp [ i , 0 ] = 0 ; } dp [ 0 , 1 ] = ( arr [ 0 ] >= 0 ? arr [ 0 ] : - 1 ) ; for ( int i = 1 ; i < N ; ++ i ) { for ( int j = 1 ; j <= ( i + 1 ) ; ++ j ) { if ( dp [ i - 1 , j ] != - 1 ) { dp [ i , j ] = Math . Max ( dp [ i , j ] , dp [ i - 1 , j ] ) ; } if ( dp [ i - 1 , j - 1 ] >= 0 && dp [ i - 1 , j - 1 ] + arr [ i ] >= 0 ) { dp [ i , j ] = Math . Max ( dp [ i , j ] , dp [ i - 1 , j - 1 ] + arr [ i ] ) ; } } } int ans = 0 ; for ( int j = 0 ; j <= N ; ++ j ) { if ( dp [ N - 1 , j ] >= 0 ) { ans = j ; } } Console . Write ( ans ) ; } public static void Main ( ) { int [ ] arr = { 4 , - 4 , 1 , - 3 , 1 , - 3 } ; int N = arr . Length ; longestSubsequence ( arr , N ) ; } }


"Longest subset of nested elements from a given array | C # program to implement the above approach ; Function to find length of longest subset such that subset { arr [ i ] , arr [ arr [ i ] ] , . . } ; Stores length of the longest subset that satisfy the condition ; Traverse in the array , arr [ ] ; If arr [ i ] equals to i ; Update res ; Count of elements in a subset ; Stores index of elements in the current subset ; Calculate length of a subset that satisfy the condition ; Make visited the current index ; Update curr_index ; Update count ; Update res ; Driver Code"
Solution in C#:

using System ; class sol { public int arrayNesting ( int [ ] arr ) { int res = 0 ; for ( int i = 0 ; i < arr . Length ; i ++ ) { if ( arr [ i ] == i ) { res = Math . Max ( res , 1 ) ; } else { int count = 0 ; int curr_index = i ; while ( arr [ curr_index ] != curr_index ) { int next_index = arr [ curr_index ] ; arr [ curr_index ] = curr_index ; curr_index = next_index ; count ++ ; } res = Math . Max ( res , count ) ; } } return res ; } } class GFG { static public void Main ( ) { sol st = new sol ( ) ; int [ ] arr = { 5 , 4 , 0 , 3 , 1 , 6 , 2 } ; int res = st . arrayNesting ( arr ) ; Console . WriteLine ( res ) ; } }


"Longest substring consisting of vowels using Binary Search | C # implementation of the above approach ; Function to check if a character is vowel or not ; 0 - a 1 - b 2 - c and so on 25 - z ; Function to check if any subString of length k exists which contains only vowels ; Applying sliding window to get all subStrings of length K ; Remove the occurence of ( i - k + 1 ) th character ; Function to perform Binary Search ; Doing binary search on the lengths ; Driver Code"
Solution in C#:

using System ; class GFG { static bool vowel ( int vo ) { if ( vo == 0 vo == 4 vo == 8 vo == 14 vo == 20 ) return true ; else return false ; } static bool check ( String s , int k ) { int [ ] cnt = new int [ 26 ] ; for ( int i = 0 ; i < k - 1 ; i ++ ) { cnt [ s [ i ] - ' a ' ] ++ ; } for ( int i = k - 1 ; i < s . Length ; i ++ ) { cnt [ s [ i ] - ' a ' ] ++ ; int flag1 = 0 ; for ( int j = 0 ; j < 26 ; j ++ ) { if ( vowel ( j ) == false && cnt [ j ] > 0 ) { flag1 = 1 ; break ; } } if ( flag1 == 0 ) return true ; cnt [ s [ i - k + 1 ] - ' a ' ] -- ; } return false ; } static int longestSubString ( String s ) { int l = 1 , r = s . Length ; int maxi = 0 ; while ( l <= r ) { int mid = ( l + r ) / 2 ; if ( check ( s , mid ) ) { l = mid + 1 ; maxi = Math . Max ( maxi , mid ) ; } else r = mid - 1 ; } return maxi ; } public static void Main ( String [ ] args ) { String s = " sedrewaefhoiu " ; Console . Write ( longestSubString ( s ) ) ; } }


"Longest substring of 0 s in a string formed by k concatenations | C # code to find maximum length of substring that contains only 0 's ; Function to calculate maximum length of substring containing only zero ; loop to first calculate longest substring in string ; if all elements in string are '0' ; Else , find size of prefix and suffix containing only zeroes ; Calculate prefix containing only zeroes ; Calculate suffix containing only zeroes ; if k <= 1 then there is no need to take prefix + suffix into account ; Driver code"
Solution in C#:

using System ; class GFG { public static int subzero ( String s , int k ) { int ans = 0 , curr = 0 ; int len = s . Length ; char [ ] str = s . ToCharArray ( ) ; for ( int i = 0 ; i < len ; ++ i ) { if ( str [ i ] == '0' ) curr ++ ; else curr = 0 ; ans = Math . Max ( ans , curr ) ; } if ( ans == len ) return len * k ; else { int pre = 0 , suff = 0 ; for ( int i = 0 ; i < len ; i ++ ) { if ( str [ i ] == '0' ) pre ++ ; else break ; } for ( int i = len - 1 ; i >= 0 ; i -- ) { if ( str [ i ] == '0' ) suff ++ ; else break ; } if ( k > 1 ) ans = Math . Max ( ans , pre + suff ) ; return ans ; } } public static void Main ( ) { String str = "00100110" ; int k = 5 ; Console . Write ( subzero ( str , k ) ) ; } }


"Longest substring of only 4 's from the first N characters of the infinite string | C # implementation of the approach ; Function to return the length of longest contiguous string containing only 4 's from the first N characters of the string ; Initialize result ; Initialize prefix sum array of characters and product variable ; Preprocessing of prefix sum array ; Initialize variable to store the string length where N belongs to ; Finding the string length where N belongs to ; Driver Code"
Solution in C#:

using System ; class GFG { static int MAXN = 30 ; static int countMaxLength ( int N ) { int res ; int [ ] pre = new int [ MAXN ] ; int p = 1 ; pre [ 0 ] = 0 ; for ( int i = 1 ; i < MAXN ; i ++ ) { p *= 2 ; pre [ i ] = pre [ i - 1 ] + i * p ; } int ind = 0 ; for ( int i = 1 ; i < MAXN ; i ++ ) { if ( pre [ i ] >= N ) { ind = i ; break ; } } int x = N - pre [ ind - 1 ] ; int y = 2 * ind - 1 ; if ( x >= y ) res = Math . Min ( x , y ) ; else res = Math . Max ( x , 2 * ( ind - 2 ) + 1 ) ; return res ; } public static void Main ( ) { int N = 25 ; Console . WriteLine ( countMaxLength ( N ) ) ; } }


"Longest substring of vowels with no two adjacent alphabets same | C # implementation of the above approach ; Function to check a character is vowel or not ; Function to check a substring is valid or not ; If size is 1 then check only first character ; If 0 'th character is  not vowel then invalid ; If two adjacent characters are same or i 'th char is  not vowel then invalid ; Function to find length of longest substring consisting only of vowels and no similar adjacent alphabets ; Stores max length of valid substring ; For current substring ; Check if substring is valid ; Size of substring is ( j - i + 1 ) ; Driver code"
Solution in C#:

using System ; class GFG { static bool isVowel ( char c ) { return ( c == ' a ' c == ' e ' c == ' i ' c == ' o ' c == ' u ' ) ; } static bool isValid ( string s ) { int n = s . Length ; if ( n == 1 ) return ( isVowel ( s [ 0 ] ) ) ; if ( isVowel ( s [ 0 ] ) == false ) return false ; for ( int i = 1 ; i < n ; i ++ ) { if ( s [ i ] == s [ i - 1 ] || ! isVowel ( s [ i ] ) ) return false ; } return true ; } static int findMaxLen ( string s ) { int maxLen = 0 ; int n = s . Length ; for ( int i = 0 ; i < n ; i ++ ) { string temp = " " ; for ( int j = i ; j < n ; j ++ ) { temp = temp + s [ j ] ; if ( isValid ( temp ) ) maxLen = Math . Max ( maxLen , ( j - i + 1 ) ) ; } } return maxLen ; } public static void Main ( ) { string Str = " aeoibsddaeiouudb " ; Console . WriteLine ( findMaxLen ( Str ) ) ; } }


"Longest substring of vowels with no two adjacent alphabets same | C # implementation of the above approach ; Function to check a character is vowel or not ; Function to find length of longest substring consisting only of vowels and no similar adjacent alphabets ; Stores max length of valid subString ; Stores length of current valid subString ; If curr and prev character are not same , include it ; If same as prev one , start new subString from here ; Store max in maxLen ; Driver code"
Solution in C#:

using System ; public class GFG { public static bool isVowel ( char x ) { return ( x == ' a ' x == ' e ' x == ' i ' x == ' o ' x == ' u ' ) ; } public static int findMaxLen ( string s ) { int maxLen = 0 ; int cur ; if ( isVowel ( s [ 0 ] ) ) maxLen = 1 ; cur = maxLen ; for ( int i = 1 ; i < s . Length ; i ++ ) { if ( isVowel ( s [ i ] ) ) { if ( s [ i ] != s [ i - 1 ] ) cur += 1 ; else cur = 1 ; } else { cur = 0 ; } maxLen = Math . Max ( cur , maxLen ) ; } return maxLen ; } public static void Main ( string [ ] args ) { string Str = " aeoibsddaeiouudb " ; Console . WriteLine ( findMaxLen ( Str ) ) ; } }


"Longest substring of vowels | C # program to find the longest substring of vowels . ; Increment current count if s [ i ] is vowel ; check previous value is greater then or not ; Driver code"
Solution in C#:

using System ; class GFG { static bool isVowel ( char c ) { return ( c == ' a ' c == ' e ' c == ' i ' c == ' o ' c == ' u ' ) ; } static int longestVowel ( String str ) { int count = 0 , res = 0 ; char [ ] s = str . ToCharArray ( ) ; for ( int i = 0 ; i < s . Length ; i ++ ) { if ( isVowel ( s [ i ] ) ) count ++ ; else { res = Math . Max ( res , count ) ; count = 0 ; } } return Math . Max ( res , count ) ; } public static void Main ( ) { String s = " theeare " ; Console . Write ( longestVowel ( s ) ) ; } }


"Longest substring that starts with X and ends with Y | C # program for the above approach ; Function returns length of longest substring starting with X and ending with Y ; Length of string ; Find the length of the string starting with X from the beginning ; Find the length of the string ending with Y from the end ; Longest substring ; Print the length ; Driver code ; Given string str ; Starting and Ending characters ; Function call"
Solution in C#:

using System ; class GFG { static void longestSubstring ( string str , char X , char Y ) { int N = str . Length ; int start = 0 ; int end = N - 1 ; int xPos = 0 ; int yPos = 0 ; while ( true ) { if ( str [ start ] == X ) { xPos = start ; break ; } start ++ ; } while ( true ) { if ( str [ end ] == Y ) { yPos = end ; break ; } end -- ; } int length = ( yPos - xPos ) + 1 ; Console . Write ( length ) ; } public static void Main ( ) { string str = " HASFJGHOGAKZZFEGA " ; char X = ' A ' , Y = ' Z ' ; longestSubstring ( str , X , Y ) ; } }


"Longest substring where all the characters appear at least K times | Set 3 | C # program to implement the above approach ; Function to find the length of the longest substring ; Store the required answer ; Create a frequency map of the characters of the string ; Store the length of the string ; Traverse the string , s ; Increment the frequency of the current character by 1 ; Stores count of unique characters ; Find the number of unique characters in string ; Iterate in range [ 1 , unique ] ; Initialize frequency of all characters as 0 ; Stores the start and the end of the window ; Stores the current number of unique characters and characters occuring atleast K times ; New unique character ; New character which occurs atleast k times ; Expand window by incrementing end by 1 ; Check if this character is present atleast k times ; Check if this character is unique ; Shrink the window by incrementing start by 1 ; If there are curr_unique characters and each character is atleast k times ; Update the overall maximum length ; Print the answer ; Driver Code"
Solution in C#:

using System ; class GFG { static void longestSubstring ( string s , int k ) { int ans = 0 ; int [ ] freq = new int [ 26 ] ; int n = s . Length ; for ( int i = 0 ; i < n ; i ++ ) freq [ s [ i ] - ' a ' ] ++ ; int unique = 0 ; for ( int i = 0 ; i < 26 ; i ++ ) if ( freq [ i ] != 0 ) unique ++ ; for ( int curr_unique = 1 ; curr_unique <= unique ; curr_unique ++ ) { for ( int i = 0 ; i < freq . Length ; i ++ ) { freq [ i ] = 0 ; } int start = 0 , end = 0 ; int cnt = 0 , count_k = 0 ; while ( end < n ) { if ( cnt <= curr_unique ) { int ind = s [ end ] - ' a ' ; if ( freq [ ind ] == 0 ) cnt ++ ; freq [ ind ] ++ ; if ( freq [ ind ] == k ) count_k ++ ; end ++ ; } else { int ind = s [ start ] - ' a ' ; if ( freq [ ind ] == k ) count_k -- ; freq [ ind ] -- ; if ( freq [ ind ] == 0 ) cnt -- ; start ++ ; } if ( cnt == curr_unique && count_k == curr_unique ) ans = Math . Max ( ans , end - start ) ; } } Console . Write ( ans ) ; } public static void Main ( ) { string S = " aabbba " ; int K = 3 ; longestSubstring ( S , K ) ; } }


"Longest substring whose characters can be rearranged to form a Palindrome | C # program for the above approach ; Function to get the length of longest substring whose characters can be arranged to form a palindromic string ; To keep track of the last index of each xor ; Initialize answer with 0 ; Now iterate through each character of the string ; Convert the character from [ a , z ] to [ 0 , 25 ] ; Turn the temp - th bit on if character occurs odd number of times and turn off the temp - th bit off if the character occurs ever number of times ; If a mask is present in the index Therefore a palindrome is found from index [ mask ] to i ; If x is not found then add its position in the index dict . ; Check for the palindrome of odd length ; We cancel the occurrence of a character if it occurs odd number times ; Driver code ; Given String ; Length of given string ; Function call"
Solution in C#:

using System . Collections . Generic ; using System ; class GFG { static int longestSubstring ( string s , int n ) { Dictionary < int , int > index = new Dictionary < int , int > ( ) ; int answer = 0 ; int mask = 0 ; index [ mask ] = - 1 ; for ( int i = 0 ; i < n ; i ++ ) { int temp = ( int ) s [ i ] - 97 ; mask ^= ( 1 << temp ) ; if ( index . ContainsKey ( mask ) == true ) { answer = Math . Max ( answer , i - index [ mask ] ) ; } else index [ mask ] = i ; for ( int j = 0 ; j < 26 ; j ++ ) { int mask2 = mask ^ ( 1 << j ) ; if ( index . ContainsKey ( mask2 ) == true ) { answer = Math . Max ( answer , i - index [ mask2 ] ) ; } } } return answer ; } public static void Main ( ) { string s = " adbabd " ; int n = s . Length ; Console . WriteLine ( longestSubstring ( s , n ) ) ; } }


"Longest substring with count of 1 s more than 0 s | C # program to find largest substring having count of 1 s more than count count of 0 s . ; Function to find longest substring having count of 1 s more than count of 0 s . ; To store sum . ; To store first occurrence of each sum value . ; To store maximum length . ; To store current substring length . ; Add 1 if current character is 1 else subtract 1. ; If sum is positive , then maximum length substring is bin [ 0. . i ] ; If sum is negative , then maximum length substring is bin [ j + 1. . i ] , where sum of substring bin [ 0. . j ] is sum - 1. ; Make entry for this sum value in hash table if this value is not present . ; Driver code"
Solution in C#:

using System ; using System . Collections . Generic ; class GFG { static int findLongestSub ( String bin ) { int n = bin . Length , i ; int sum = 0 ; Dictionary < int , int > prevSum = new Dictionary < int , int > ( ) ; int maxlen = 0 ; int currlen ; for ( i = 0 ; i < n ; i ++ ) { if ( bin [ i ] == '1' ) sum ++ ; else sum -- ; if ( sum > 0 ) { maxlen = i + 1 ; } else if ( sum <= 0 ) { if ( prevSum . ContainsKey ( sum - 1 ) ) { currlen = i - ( prevSum [ sum - 1 ] == 0 ? 1 : prevSum [ sum - 1 ] ) ; maxlen = Math . Max ( maxlen , currlen ) ; } } if ( ! prevSum . ContainsKey ( sum ) ) prevSum . Add ( sum , i ) ; } return maxlen ; } public static void Main ( String [ ] args ) { String bin = "1010" ; Console . WriteLine ( findLongestSub ( bin ) ) ; } }


"Longest substring with no pair of adjacent characters are adjacent English alphabets | C # program for the above approach ; Function to find the longest substring satisfying the given condition ; Stores all temporary substrings ; Stores the longest substring ; Stores the length of the substring T ; Stores the first character of string S ; Traverse the string ; If the absolute difference is 1 ; Update the length of substring T ; Update the longest substring ; Otherwise , stores the current character ; Again checking for longest substring and update accordingly ; Print the longest substring ; Driver Code ; Given string ; Function call to find the longest substring satisfying given condition"
Solution in C#:

using System ; public class GFG { static void findSubstring ( string S ) { string T = " " ; string ans = " " ; int l = 0 ; T += S [ 0 ] ; for ( int i = 1 ; i < S . Length ; i ++ ) { if ( Math . Abs ( S [ i ] - S [ i - 1 ] ) == 1 ) { l = T . Length ; if ( l > ans . Length ) { ans = T ; } T = " " ; T += S [ i ] ; } else { T += S [ i ] ; } } l = T . Length ; if ( l > ans . Length ) { ans = T ; } Console . Write ( ans ) ; } public static void Main ( String [ ] args ) { string S = " aabdml " ; findSubstring ( S ) ; } }


"Longest suffix such that occurrence of each character is less than N after deleting atmost K characters | C # implementation to find longest suffix of the String such that occurrence of each character is less than K ; Function to find the maximum length suffix in the String ; Length of the String ; Map to store the number of occurrence of character ; Loop to iterate String from the last character ; Condition to check if the occurrence of each character is less than given number ; Condition when character cannot be deleted ; longest suffix ; Driver Code ; Function call"
Solution in C#:

using System ; class GFG { static void maximumSuffix ( String s , int n , int k ) { int i = s . Length - 1 ; int [ ] arr = new int [ 26 ] ; String suffix = " " ; while ( i > - 1 ) { int index = s [ i ] - ' a ' ; if ( arr [ index ] < n ) { arr [ index ] ++ ; suffix += s [ i ] ; i -- ; continue ; } if ( k == 0 ) break ; k -- ; i -- ; } suffix = reverse ( suffix ) ; Console . Write ( suffix ) ; } static String reverse ( String input ) { char [ ] a = input . ToCharArray ( ) ; int l , r = a . Length - 1 ; for ( l = 0 ; l < r ; l ++ , r -- ) { char temp = a [ l ] ; a [ l ] = a [ r ] ; a [ r ] = temp ; } return String . Join ( " " , a ) ; } public static void Main ( String [ ] args ) { String str = " iahagafedcba " ; int n = 1 , k = 2 ; maximumSuffix ( str , n , k ) ; } }


"Lower case to upper case | C # program to convert a string to uppercase ; Converts a string to uppercase ; Driver code"
Solution in C#:

using System ; class GFG { static String to_upper ( char [ ] In ) { for ( int i = 0 ; i < In . Length ; i ++ ) { if ( ' a ' <= In [ i ] & In [ i ] <= ' z ' ) { In [ i ] = ( char ) ( In [ i ] - ' a ' + ' A ' ) ; } } return String . Join ( " " , In ) ; } public static void Main ( ) { String str = " geeksforgeeks " ; Console . WriteLine ( to_upper ( str . ToCharArray ( ) ) ) ; } }


using System ; class GFG { static String to_upper ( char [ ] str ) { for ( int i = 0 ; i < str . Length ; i ++ ) if ( ' a ' <= str [ i ] && str [ i ] <= ' z ' ) str [ i ] = ( char ) ( ( int ) str [ i ] & ( ~ ( 1 << 5 ) ) ) ; return String . Join ( " " , str ) ; } public static void Main ( String [ ] args ) { String str = " geeksforgeeks " ; Console . WriteLine ( to_upper ( str . ToCharArray ( ) ) ) ; } }


"Lowest Common Ancestor for a Set of Nodes in a Rooted Tree | C # Program to find the LCA in a rooted tree for a given set of nodes ; Set time 1 initially ; Case for root node ; In - time for node ; Out - time for the node ; level [ i ] - . Level of node i ; t_in [ i ] - . In - time of node i ; t_out [ i ] - . Out - time of node i ; Fill the level , in - time and out - time of all nodes ; To find minimum in - time among all nodes in LCA set ; To find maximum in - time among all nodes in LCA set ; Node with same minimum and maximum out time is LCA for the set ; Take the minimum level as level of LCA ; If i - th node is at a higher level than that of the minimum among the nodes of the given set ; Compare in - time , out - time and level of i - th node to the respective extremes among all nodes of the given set ; Driver code"
Solution in C#:

 using System ; using System . Collections . Generic ; public class GFG { static int T = 1 ; static void dfs ( int node , int parent , List < int > [ ] g , int [ ] level , int [ ] t_in , int [ ] t_out ) { if ( parent == - 1 ) { level [ node ] = 1 ; } else { level [ node ] = level [ parent ] + 1 ; } t_in [ node ] = T ; foreach ( int i in g [ node ] ) { if ( i != parent ) { T ++ ; dfs ( i , node , g , level , t_in , t_out ) ; } } T ++ ; t_out [ node ] = T ; } static int findLCA ( int n , List < int > [ ] g , List < int > v ) { int [ ] level = new int [ n + 1 ] ; int [ ] t_in = new int [ n + 1 ] ; int [ ] t_out = new int [ n + 1 ] ; dfs ( 1 , - 1 , g , level , t_in , t_out ) ; int mint = int . MaxValue , maxt = int . MinValue ; int minv = - 1 , maxv = - 1 ; for ( int i = 0 ; i < v . Count ; i ++ ) { if ( t_in [ v [ i ] ] < mint ) { mint = t_in [ v [ i ] ] ; minv = v [ i ] ; } if ( t_out [ v [ i ] ] > maxt ) { maxt = t_out [ v [ i ] ] ; maxv = v [ i ] ; } } if ( minv == maxv ) { return minv ; } int lev = Math . Min ( level [ minv ] , level [ maxv ] ) ; int node = 0 , l = int . MinValue ; for ( int i = 1 ; i <= n ; i ++ ) { if ( level [ i ] > lev ) continue ; if ( t_in [ i ] <= mint && t_out [ i ] >= maxt && level [ i ] > l ) { node = i ; l = level [ i ] ; } } return node ; } public static void Main ( String [ ] args ) { int n = 10 ; List < int > [ ] g = new List < int > [ n + 1 ] ; for ( int i = 0 ; i < g . Length ; i ++ ) g [ i ] = new List < int > ( ) ; g [ 1 ] . Add ( 2 ) ; g [ 2 ] . Add ( 1 ) ; g [ 1 ] . Add ( 3 ) ; g [ 3 ] . Add ( 1 ) ; g [ 1 ] . Add ( 4 ) ; g [ 4 ] . Add ( 1 ) ; g [ 2 ] . Add ( 5 ) ; g [ 5 ] . Add ( 2 ) ; g [ 2 ] . Add ( 6 ) ; g [ 6 ] . Add ( 2 ) ; g [ 3 ] . Add ( 7 ) ; g [ 7 ] . Add ( 3 ) ; g [ 4 ] . Add ( 10 ) ; g [ 10 ] . Add ( 4 ) ; g [ 8 ] . Add ( 7 ) ; g [ 7 ] . Add ( 8 ) ; g [ 9 ] . Add ( 7 ) ; g [ 7 ] . Add ( 9 ) ; List < int > v = new List < int > ( ) ; v . Add ( 7 ) ; v . Add ( 3 ) ; v . Add ( 8 ) ; Console . Write ( findLCA ( n , g , v ) + "
 " ) ; } }


"Lowest Common Ancestor in Parent Array Representation | C # program to find LCA in a tree represented as parent array . ; Maximum value in a node ; Function to find the Lowest common ancestor ; Create a visited vector and mark all nodes as not visited . ; Moving from n1 node till root and mark every accessed node as visited ; Move to the parent of node n1 ; For second node finding the first node common ; Insert function for Binary tree ; Driver Code ; Maximum capacity of binary tree ; Root marked"
Solution in C#:

using System ; class GFG { static int MAX = 1000 ; static int findLCA ( int n1 , int n2 , int [ ] parent ) { Boolean [ ] visited = new Boolean [ MAX ] ; visited [ n1 ] = true ; while ( parent [ n1 ] != - 1 ) { visited [ n1 ] = true ; n1 = parent [ n1 ] ; } visited [ n1 ] = true ; while ( ! visited [ n2 ] ) n2 = parent [ n2 ] ; return n2 ; } static void insertAdj ( int [ ] parent , int i , int j ) { parent [ i ] = j ; } public static void Main ( String [ ] args ) { int [ ] parent = new int [ MAX ] ; parent [ 20 ] = - 1 ; insertAdj ( parent , 8 , 20 ) ; insertAdj ( parent , 22 , 20 ) ; insertAdj ( parent , 4 , 8 ) ; insertAdj ( parent , 12 , 8 ) ; insertAdj ( parent , 10 , 12 ) ; insertAdj ( parent , 14 , 12 ) ; Console . WriteLine ( findLCA ( 10 , 14 , parent ) ) ; } }


"Lowest Common Ancestor in a Binary Search Tree . | Recursive C # program to print lca of two nodes A binary tree node ; Function to find LCA of n1 and n2 . The function assumes that both n1 and n2 are present in BST ; If both n1 and n2 are smaller than root , then LCA lies in left ; If both n1 and n2 are greater than root , then LCA lies in right ; Driver program to test lca ( ) ; Let us construct the BST shown in the above figure"
Solution in C#:

using System ; public class Node { public int data ; public Node left , right ; public Node ( int item ) { data = item ; left = right = null ; } } public class BinaryTree { public Node root ; public virtual Node lca ( Node root , int n1 , int n2 ) { while ( root != null ) { if ( root . data > n1 && root . data > n2 ) root = root . left ; else if ( root . data < n1 && root . data < n2 ) root = root . right ; else break ; } return root ; } public static void Main ( string [ ] args ) { BinaryTree tree = new BinaryTree ( ) ; tree . root = new Node ( 20 ) ; tree . root . left = new Node ( 8 ) ; tree . root . right = new Node ( 22 ) ; tree . root . left . left = new Node ( 4 ) ; tree . root . left . right = new Node ( 12 ) ; tree . root . left . right . left = new Node ( 10 ) ; tree . root . left . right . right = new Node ( 14 ) ; int n1 = 10 , n2 = 14 ; Node t = tree . lca ( tree . root , n1 , n2 ) ; Console . WriteLine ( " LCA ▁ of ▁ " + n1 + " ▁ and ▁ " + n2 + " ▁ is ▁ " + t . data ) ; n1 = 14 ; n2 = 8 ; t = tree . lca ( tree . root , n1 , n2 ) ; Console . WriteLine ( " LCA ▁ of ▁ " + n1 + " ▁ and ▁ " + n2 + " ▁ is ▁ " + t . data ) ; n1 = 10 ; n2 = 22 ; t = tree . lca ( tree . root , n1 , n2 ) ; Console . WriteLine ( " LCA ▁ of ▁ " + n1 + " ▁ and ▁ " + n2 + " ▁ is ▁ " + t . data ) ; } }


"Lowest Common Ancestor in a Binary Tree | Set 1 | C # implementation to find lowest common ancestor of n1 and n2 using one traversal of binary tree ; Class containing left and right child of current node and key value ; Root of the Binary Tree ; This function returns pointer to LCA of two given values n1 and n2 . This function assumes that n1 and n2 are present in Binary Tree ; Base case ; If either n1 or n2 matches with root 's key, report the presence  by returning root (Note that if  a key is ancestor of other,  then the ancestor key becomes LCA ; Look for keys in left and right subtrees ; If both of the above calls return Non - NULL , then one key is present in once subtree and other is present in other , So this node is the LCA ; Otherwise check if left subtree or right subtree is LCA ; Driver code"
Solution in C#:

using System ; public class Node { public int data ; public Node left , right ; public Node ( int item ) { data = item ; left = right = null ; } } class BinaryTree { Node root ; Node findLCA ( int n1 , int n2 ) { return findLCA ( root , n1 , n2 ) ; } Node findLCA ( Node node , int n1 , int n2 ) { if ( node == null ) return null ; if ( node . data == n1 node . data == n2 ) return node ; Node left_lca = findLCA ( node . left , n1 , n2 ) ; Node right_lca = findLCA ( node . right , n1 , n2 ) ; if ( left_lca != null && right_lca != null ) return node ; return ( left_lca != null ) ? left_lca : right_lca ; } public static void Main ( string [ ] args ) { BinaryTree tree = new BinaryTree ( ) ; tree . root = new Node ( 1 ) ; tree . root . left = new Node ( 2 ) ; tree . root . right = new Node ( 3 ) ; tree . root . left . left = new Node ( 4 ) ; tree . root . left . right = new Node ( 5 ) ; tree . root . right . left = new Node ( 6 ) ; tree . root . right . right = new Node ( 7 ) ; Console . WriteLine ( " LCA ( 4 , ▁ 5 ) ▁ = ▁ " + tree . findLCA ( 4 , 5 ) . data ) ; Console . WriteLine ( " LCA ( 4 , ▁ 6 ) ▁ = ▁ " + tree . findLCA ( 4 , 6 ) . data ) ; Console . WriteLine ( " LCA ( 3 , ▁ 4 ) ▁ = ▁ " + tree . findLCA ( 3 , 4 ) . data ) ; Console . WriteLine ( " LCA ( 2 , ▁ 4 ) ▁ = ▁ " + tree . findLCA ( 2 , 4 ) . data ) ; } }


"Lowest Common Ancestor in a Binary Tree | Set 1 | c # implementation to find lowest common ancestor of n1 and n2 using one traversal of binary tree It also handles cases even when n1 and n2 are not there in Tree ; Class containing left and right child of current node and key ; Root of the Binary Tree ; This function returns pointer to LCA of two given values n1 and n2 . v1 is set as true by this function if n1 is found v2 is set as true by this function if n2 is found ; Base case ; Store result in temp , in case of key match so that we can search for other key also . ; If either n1 or n2 matches with root 's key, report the presence  by setting v1 or v2 as true and return root (Note that if a key is ancestor of other, then the ancestor key becomes LCA) ; Look for keys in left and right subtrees ; If both of the above calls return Non - NULL , then one key is present in once subtree and other is present in other , So this node is the LCA ; Otherwise check if left subtree or right subtree is LCA ; Finds lca of n1 and n2 under the subtree rooted with ' node ' ; Initialize n1 and n2 as not visited ; Find lca of n1 and n2 using the technique discussed above ; Return LCA only if both n1 and n2 are present in tree ; Else return NULL ; Driver program to test above functions"
Solution in C#:

using System ; public class Node { public int data ; public Node left , right ; public Node ( int item ) { data = item ; left = right = null ; } } public class BinaryTree { public Node root ; public static bool v1 = false , v2 = false ; public virtual Node findLCAUtil ( Node node , int n1 , int n2 ) { if ( node == null ) { return null ; } Node temp = null ; if ( node . data == n1 ) { v1 = true ; temp = node ; } if ( node . data == n2 ) { v2 = true ; temp = node ; } Node left_lca = findLCAUtil ( node . left , n1 , n2 ) ; Node right_lca = findLCAUtil ( node . right , n1 , n2 ) ; if ( temp != null ) { return temp ; } if ( left_lca != null && right_lca != null ) { return node ; } return ( left_lca != null ) ? left_lca : right_lca ; } public virtual Node findLCA ( int n1 , int n2 ) { v1 = false ; v2 = false ; Node lca = findLCAUtil ( root , n1 , n2 ) ; if ( v1 && v2 ) { return lca ; } return null ; } public static void Main ( string [ ] args ) { BinaryTree tree = new BinaryTree ( ) ; tree . root = new Node ( 1 ) ; tree . root . left = new Node ( 2 ) ; tree . root . right = new Node ( 3 ) ; tree . root . left . left = new Node ( 4 ) ; tree . root . left . right = new Node ( 5 ) ; tree . root . right . left = new Node ( 6 ) ; tree . root . right . right = new Node ( 7 ) ; Node lca = tree . findLCA ( 4 , 5 ) ; if ( lca != null ) { Console . WriteLine ( " LCA ( 4 , ▁ 5 ) ▁ = ▁ " + lca . data ) ; } else { Console . WriteLine ( " Keys ▁ are ▁ not ▁ present " ) ; } lca = tree . findLCA ( 4 , 10 ) ; if ( lca != null ) { Console . WriteLine ( " LCA ( 4 , ▁ 10 ) ▁ = ▁ " + lca . data ) ; } else { Console . WriteLine ( " Keys ▁ are ▁ not ▁ present " ) ; } } }


"Lowest Common Ancestor in a Binary Tree | Set 2 ( Using Parent Pointer ) | A tree node ; A utility function to insert a new node with given key in Binary Search Tree ; If the tree is empty , return a new node ; Otherwise , recur down the tree ; return the ( unchanged ) node pointer ; To find LCA of nodes n1 and n2 in Binary Tree ; Creata a map to store ancestors of n1 ; Insert n1 and all its ancestors in map ; Check if n2 or any of its ancestors is in map . ; Driver code"
Solution in C#:

using System ; using System . Collections ; using System . Collections . Generic ; public class Node { public int key ; public Node left , right , parent ; public Node ( int key ) { this . key = key ; left = right = parent = null ; } } class BinaryTree { Node root , n1 , n2 , lca ; Node insert ( Node node , int key ) { if ( node == null ) return new Node ( key ) ; if ( key < node . key ) { node . left = insert ( node . left , key ) ; node . left . parent = node ; } else if ( key > node . key ) { node . right = insert ( node . right , key ) ; node . right . parent = node ; } return node ; } Node LCA ( Node n1 , Node n2 ) { Dictionary < Node , Boolean > ancestors = new Dictionary < Node , Boolean > ( ) ; while ( n1 != null ) { ancestors . Add ( n1 , true ) ; n1 = n1 . parent ; } while ( n2 != null ) { if ( ancestors . ContainsKey ( n2 ) ) return n2 ; n2 = n2 . parent ; } return null ; } public static void Main ( String [ ] args ) { BinaryTree tree = new BinaryTree ( ) ; tree . root = tree . insert ( tree . root , 20 ) ; tree . root = tree . insert ( tree . root , 8 ) ; tree . root = tree . insert ( tree . root , 22 ) ; tree . root = tree . insert ( tree . root , 4 ) ; tree . root = tree . insert ( tree . root , 12 ) ; tree . root = tree . insert ( tree . root , 10 ) ; tree . root = tree . insert ( tree . root , 14 ) ; tree . n1 = tree . root . left . right . left ; tree . n2 = tree . root . left ; tree . lca = tree . LCA ( tree . n1 , tree . n2 ) ; Console . WriteLine ( " LCA ▁ of ▁ " + tree . n1 . key + " ▁ and ▁ " + tree . n2 . key + " ▁ is ▁ " + tree . lca . key ) ; } }


"Lowest Common Ancestor in a Binary Tree | Set 2 ( Using Parent Pointer ) | C # program to find lowest common ancestor using parent pointer ; A tree node ; A utility function to insert a new node with given key in Binary Search Tree ; If the tree is empty , return a new node ; Otherwise , recur down the tree ; return the ( unchanged ) node pointer ; A utility function to find depth of a node ( distance of it from root ) ; To find LCA of nodes n1 and n2 in Binary Tree ; Find depths of two nodes and differences ; If n2 is deeper , swap n1 and n2 ; Move n1 up until it reaches the same level as n2 ; Now n1 and n2 are at same levels ; Driver Code"
Solution in C#:

using System ; public class Node { public int key ; public Node left , right , parent ; public Node ( int key ) { this . key = key ; left = right = parent = null ; } } class GFG { public Node root , n1 , n2 , lca ; public virtual Node insert ( Node node , int key ) { if ( node == null ) { return new Node ( key ) ; } if ( key < node . key ) { node . left = insert ( node . left , key ) ; node . left . parent = node ; } else if ( key > node . key ) { node . right = insert ( node . right , key ) ; node . right . parent = node ; } return node ; } public virtual int depth ( Node node ) { int d = - 1 ; while ( node != null ) { ++ d ; node = node . parent ; } return d ; } public virtual Node LCA ( Node n1 , Node n2 ) { int d1 = depth ( n1 ) , d2 = depth ( n2 ) ; int diff = d1 - d2 ; if ( diff < 0 ) { Node temp = n1 ; n1 = n2 ; n2 = temp ; diff = - diff ; } while ( diff -- != 0 ) { n1 = n1 . parent ; } while ( n1 != null && n2 != null ) { if ( n1 == n2 ) { return n1 ; } n1 = n1 . parent ; n2 = n2 . parent ; } return null ; } public static void Main ( string [ ] args ) { GFG tree = new GFG ( ) ; tree . root = tree . insert ( tree . root , 20 ) ; tree . root = tree . insert ( tree . root , 8 ) ; tree . root = tree . insert ( tree . root , 22 ) ; tree . root = tree . insert ( tree . root , 4 ) ; tree . root = tree . insert ( tree . root , 12 ) ; tree . root = tree . insert ( tree . root , 10 ) ; tree . root = tree . insert ( tree . root , 14 ) ; tree . n1 = tree . root . left . right . left ; tree . n2 = tree . root . right ; tree . lca = tree . LCA ( tree . n1 , tree . n2 ) ; Console . WriteLine ( " LCA ▁ of ▁ " + tree . n1 . key + " ▁ and ▁ " + tree . n2 . key + " ▁ is ▁ " + tree . lca . key ) ; } }


"Lowest Common Ancestor in a Binary Tree | Set 3 ( Using RMQ ) | C # code to find LCA of given two nodes in a tree ; the graph ; level of each node ; the segment tree ; adding edges to the graph ( tree ) ; assigning level to nodes ; storing the dfs traversal in the array e ; making the array l ; making the array h ; if is already stored ; Range minimum query to return the index of minimum in the subarray L [ qs : qe ] ; out of range ; in the range ; constructs the segment tree ; leaf ; Function to get LCA ; Driver code ; n = number of nodes in the tree q = number of queries to answer ; 1 / | \ 2 3 4 | \ 5 6 / | \ 8 7 9 ( right of 5 ) / | \ | \ 10 11 12 13 14 | 15"
Solution in C#:

using System ; using System . Collections . Generic ; public class GFG { static int maxn = 100005 ; static int left ( int i ) { return ( 2 * i + 1 ) ; } static int right ( int i ) { return 2 * i + 2 ; } static List < int > [ ] g = new List < int > [ maxn ] ; static int [ ] level = new int [ maxn ] ; static List < int > e = new List < int > ( ) ; static List < int > l = new List < int > ( ) ; static int [ ] h = new int [ maxn ] ; static int [ ] st ; static void add_edge ( int u , int v ) { g [ u ] . Add ( v ) ; g [ v ] . Add ( u ) ; } static void leveling ( int src ) { for ( int i = 0 ; i < ( g [ src ] . Count ) ; i ++ ) { int des = g [ src ] [ i ] ; if ( level [ des ] != 0 ) { level [ des ] = level [ src ] + 1 ; leveling ( des ) ; } } } static bool [ ] visited = new bool [ maxn ] ; static void dfs ( int src ) { e . Add ( src ) ; visited [ src ] = true ; for ( int i = 0 ; i < ( g [ src ] ) . Count ; i ++ ) { int des = g [ src ] [ i ] ; if ( ! visited [ des ] ) { dfs ( des ) ; e . Add ( src ) ; } } } static void setting_l ( int n ) { for ( int i = 0 ; i < e . Count ; i ++ ) l . Add ( level [ e [ i ] ] ) ; } static void setting_h ( int n ) { for ( int i = 0 ; i <= n ; i ++ ) h [ i ] = - 1 ; for ( int i = 0 ; i < e . Count ; i ++ ) { if ( h [ e [ i ] ] == - 1 ) h [ e [ i ] ] = i ; } } static int RMQ ( int ss , int se , int qs , int qe , int i ) { if ( ss > se ) return - 1 ; if ( se < qs < ss ) return - 1 ; if ( qs <= ss && se <= qe ) return st [ i ] ; int mid = ( ss + se ) / 2 ; int sti = RMQ ( ss , mid , qs , qe , left ( i ) ) ; int en = RMQ ( mid + 1 , se , qs , qe , right ( i ) ) ; if ( sti != - 1 && en != - 1 ) { if ( l [ sti ] < l [ en ] ) return sti ; return en ; } else if ( sti != - 1 ) return sti - 2 ; else if ( en != - 1 ) return en - 1 ; return 0 ; } static void SegmentTreeConstruction ( int ss , int se , int i ) { if ( ss > se ) return ; if ( ss == se ) { st [ i ] = ss ; return ; } int mid = ( ss + se ) / 2 ; SegmentTreeConstruction ( ss , mid , left ( i ) ) ; SegmentTreeConstruction ( mid + 1 , se ,...


"Lowest Common Ancestor of the deepest leaves of a Binary Tree | C # program for the above approach ; Node of a Binary Tree ; Function to find the depth of the Binary Tree ; If root is not null ; Left recursive subtree ; Right recursive subtree ; Returns the maximum depth ; Function to perform the depth first search on the binary tree ; If root is null ; If curr is equal to depth ; Left recursive subtree ; Right recursive subtree ; If left and right are not null ; Return left , if left is not null Otherwise return right ; Function to find the LCA of the deepest nodes of the binary tree ; If root is null ; Stores the deepest depth of the binary tree ; Return the LCA of the nodes at level depth ; Driver code ; Given Binary Tree"
Solution in C#:

using System ; class Node { public Node left = null ; public Node right = null ; public int data ; public Node ( int data ) { this . data = data ; } } public class GFG { static int findDepth ( Node root ) { if ( root == null ) return 0 ; int left = findDepth ( root . left ) ; int right = findDepth ( root . right ) ; return 1 + Math . Max ( left , right ) ; } static Node DFS ( Node root , int curr , int depth ) { if ( root == null ) return null ; if ( curr == depth ) return root ; Node left = DFS ( root . left , curr + 1 , depth ) ; Node right = DFS ( root . right , curr + 1 , depth ) ; if ( left != null && right != null ) return root ; return ( left != null ) ? left : right ; } static Node lcaOfDeepestLeaves ( Node root ) { if ( root == null ) return null ; int depth = findDepth ( root ) - 1 ; return DFS ( root , 0 , depth ) ; } public static void Main ( String [ ] args ) { Node root = new Node ( 1 ) ; root . left = new Node ( 2 ) ; root . right = new Node ( 3 ) ; root . left . left = new Node ( 4 ) ; root . left . right = new Node ( 5 ) ; root . right . left = new Node ( 6 ) ; root . right . right = new Node ( 7 ) ; root . right . left . left = new Node ( 8 ) ; root . right . left . right = new Node ( 9 ) ; Console . WriteLine ( lcaOfDeepestLeaves ( root ) . data ) ; } }


"Lucas Numbers | Iterative C # program to find n 'th Lucas Number ; Iterative function ; declaring base values for positions 0 and 1 ; generating number ; Driver Code"
Solution in C#:

using System ; class GFG { static int lucas ( int n ) { int a = 2 , b = 1 , c , i ; if ( n == 0 ) return a ; for ( i = 2 ; i <= n ; i ++ ) { c = a + b ; a = b ; b = c ; } return b ; } public static void Main ( ) { int n = 9 ; Console . WriteLine ( lucas ( n ) ) ; } }


"Lucas Numbers | Recursive C # program to find n 'th Lucas number ; recursive function ; Base cases ; recurrence relation ; Driver program"
Solution in C#:

using System ; class GFG { public static int lucas ( int n ) { if ( n == 0 ) return 2 ; if ( n == 1 ) return 1 ; return lucas ( n - 1 ) + lucas ( n - 2 ) ; } public static void Main ( ) { int n = 9 ; Console . WriteLine ( lucas ( n ) ) ; } }


"Lucky Numbers | C # program to check Lucky Number ; Returns 1 if n is a lucky no . ohterwise returns 0 ; variable next_position is just for readability of the program we can remove it and use n only ; calculate next position of input no ; driver program"
Solution in C#:

using System ; class GFG { public static int counter = 2 ; static bool isLucky ( int n ) { int next_position = n ; if ( counter > n ) return true ; if ( n % counter == 0 ) return false ; next_position -= next_position / counter ; counter ++ ; return isLucky ( next_position ) ; } public static void Main ( ) { int x = 5 ; if ( isLucky ( x ) ) Console . Write ( x + " ▁ is ▁ a ▁ " + " lucky ▁ no . " ) ; else Console . Write ( x + " ▁ is ▁ not " + " ▁ a ▁ lucky ▁ no . " ) ; } }


"Lucky alive person in a circle | Code Solution to sword puzzle | C # code to find the luckiest person ; Node structure ; Function to find the luckiest person ; Create a single node circular linked list . ; Starting from first soldier . ; condition for evaluating the existence of single soldier who is not killed . ; deleting soldier from the circular list who is killed in the fight . ; Returning the Luckiest soldier who remains alive . ; Driver code"
Solution in C#:

using System ; class GFG { public class Node { public int data ; public Node next ; } ; static Node newNode ( int data ) { Node node = new Node ( ) ; node . data = data ; node . next = null ; return node ; } static int alivesol ( int Num ) { if ( Num == 1 ) return 1 ; Node last = newNode ( 1 ) ; last . next = last ; for ( int i = 2 ; i <= Num ; i ++ ) { Node tem = newNode ( i ) ; tem . next = last . next ; last . next = tem ; last = tem ; } Node curr = last . next ; Node tem1 = new Node ( ) ; while ( curr . next != curr ) { tem1 = curr ; curr = curr . next ; tem1 . next = curr . next ; tem1 = tem1 . next ; curr = tem1 ; } int res = tem1 . data ; return res ; } public static void Main ( String [ ] args ) { int N = 100 ; Console . WriteLine ( alivesol ( N ) ) ; } }


"Lucky alive person in a circle | Set | C # implementation of the above approach ; To calculate the number of bits in the binary equivalent of n ; Finding complement by inverting the bits one by one from last ; XOR of n2 with ( 1 << i ) to flip the last ( i + 1 ) th bit of binary equivalent of n2 ; n2 will be the one 's complement of n ; Driver code"
Solution in C#:

using System ; class GFG { static int luckiest_person ( int n ) { int len = ( int ) ( Math . Log ( n ) / Math . Log ( 2 ) ) + 1 ; int n2 = n ; for ( int i = 0 ; i < len ; i ++ ) { n2 = n2 ^ ( 1 << i ) ; } return Math . Abs ( n - n2 ) ; } public static void Main ( ) { int N = 3 ; int lucky_p = luckiest_person ( N ) ; Console . Write ( lucky_p ) ; } }