codeparrot/xlcost-text-to-code huggingface dataset:
Shortest path with exactly k edges in a directed and weighted graph | Dynamic Programming based C # program to find shortest pathwith exactly k edges ; Define number of vertices in the graph and inifinite value ; A naive recursive function to count walks from u to v with k edges ; Base cases ; Initialize result ; Go to all adjacents of u and recur ; Driver Code ; Let us create the graph shown in above diagram
using System ; class GFG { const int V = 4 ; const int INF = Int32 . MaxValue ; int shortestPath ( int [ , ] graph , int u , int v , int k ) { if ( k == 0 && u == v ) return 0 ; if ( k == 1 && graph [ u , v ] != INF ) return graph [ u , v ] ; if ( k <= 0 ) return INF ; int res = INF ; for ( int i = 0 ; i < V ; i ++ ) { if ( graph [ u , i ] != INF && u != i && v != i ) { int rec_res = shortestPath ( graph , i , v , k - 1 ) ; if ( rec_res != INF ) res = Math . Min ( res , graph [ u , i ] + rec_res ) ; } } return res ; } public static void Main ( ) { int [ , ] graph = new int [ , ] { { 0 , 10 , 3 , 2 } , { INF , 0 , INF , 7 } , { INF , INF , 0 , 6 } , { INF , INF , INF , 0 } } ; GFG t = new GFG ( ) ; int u = 0 , v = 3 , k = 2 ; Console . WriteLine ( " Weight ▁ of ▁ the ▁ shortest ▁ path ▁ is ▁ " + t . shortestPath ( graph , u , v , k ) ) ; } }
Shortest path with exactly k edges in a directed and weighted graph | Dynamic Programming based C # program to find shortest path with exactly k edges ; Define number of vertices in the graph and inifinite value ; A Dynamic programming based function to find the shortest path from u to v with exactly k edges . ; Table to be filled up using DP . The value sp [ i ] [ j ] [ e ] will store weight of the shortest path from i to j with exactly k edges ; Loop for number of edges from 0 to k ; for source ; for destination ; initialize value ; from base cases ; go to adjacent only when number of edges is more than 1 ; There should be an edge from i to a and a should not be same as either i or j ; Driver Code ; Let us create the graph shown in above diagram
using System ; class GFG { static readonly int V = 4 ; static readonly int INF = int . MaxValue ; int shortestPath ( int [ , ] graph , int u , int v , int k ) { int [ , , ] sp = new int [ V , V , k + 1 ] ; for ( int e = 0 ; e <= k ; e ++ ) { for ( int i = 0 ; i < V ; i ++ ) { for ( int j = 0 ; j < V ; j ++ ) { sp [ i , j , e ] = INF ; if ( e == 0 && i == j ) sp [ i , j , e ] = 0 ; if ( e == 1 && graph [ i , j ] != INF ) sp [ i , j , e ] = graph [ i , j ] ; if ( e > 1 ) { for ( int a = 0 ; a < V ; a ++ ) { if ( graph [ i , a ] != INF && i != a && j != a && sp [ a , j , e - 1 ] != INF ) sp [ i , j , e ] = Math . Min ( sp [ i , j , e ] , graph [ i , a ] + sp [ a , j , e - 1 ] ) ; } } } } } return sp [ u , v , k ] ; } public static void Main ( String [ ] args ) { int [ , ] graph = new int [ , ] { { 0 , 10 , 3 , 2 } , { INF , 0 , INF , 7 } , { INF , INF , 0 , 6 } , { INF , INF , INF , 0 } } ; GFG t = new GFG ( ) ; int u = 0 , v = 3 , k = 2 ; Console . WriteLine ( " Weight ▁ of ▁ the ▁ shortest ▁ path ▁ is ▁ " + t . shortestPath ( graph , u , v , k ) ) ; } }
Multistage Graph ( Shortest Path ) | C # program to find shortest distance in a multistage graph . ; Returns shortest distance from 0 to N - 1. ; dist [ i ] is going to store shortest distance from node i to node N - 1. ; Calculating shortest path for rest of the nodes ; Initialize distance from i to destination ( N - 1 ) ; Check all nodes of next stages to find shortest distance from i to N - 1. ; Reject if no edge exists ; We apply recursive equation to distance to target through j . and compare with minimum distance so far . ; Driver code ; Graph stored in the form of an adjacency Matrix
using System ; class GFG { static int N = 8 ; static int INF = int . MaxValue ; public static int shortestDist ( int [ , ] graph ) { int [ ] dist = new int [ N ] ; dist [ N - 1 ] = 0 ; for ( int i = N - 2 ; i >= 0 ; i -- ) { dist [ i ] = INF ; for ( int j = i ; j < N ; j ++ ) { if ( graph [ i , j ] == INF ) continue ; dist [ i ] = Math . Min ( dist [ i ] , graph [ i , j ] + dist [ j ] ) ; } } return dist [ 0 ] ; } static void Main ( ) { int [ , ] graph = new int [ , ] { { INF , 1 , 2 , 5 , INF , INF , INF , INF } , { INF , INF , INF , INF , 4 , 11 , INF , INF } , { INF , INF , INF , INF , 9 , 5 , 16 , INF } , { INF , INF , INF , INF , INF , INF , 2 , INF } , { INF , INF , INF , INF , INF , INF , INF , 18 } , { INF , INF , INF , INF , INF , INF , INF , 13 } , { INF , INF , INF , INF , INF , INF , INF , 2 } } ; Console . Write ( shortestDist ( graph ) ) ; } }
Reverse Level Order Traversal | A recursive C # program to print reverse level order traversal ; A binary tree node ; Function to print REVERSE level order traversal a tree ; Print nodes at a given level ; Compute the " height " of a tree -- the number of nodes along the longest path from the root node down to the farthest leaf node . ; compute the height of each subtree ; use the larger one ; Driver Code ; Let us create trees shown in above diagram
using System ; class Node { public int data ; public Node left , right ; public Node ( int item ) { data = item ; left = right ; } } class BinaryTree { Node root ; void reverseLevelOrder ( Node node ) { int h = height ( node ) ; int i ; for ( i = h ; i >= 1 ; i -- ) { printGivenLevel ( node , i ) ; } } void printGivenLevel ( Node node , int level ) { if ( node == null ) return ; if ( level == 1 ) Console . Write ( node . data + " ▁ " ) ; else if ( level > 1 ) { printGivenLevel ( node . left , level - 1 ) ; printGivenLevel ( node . right , level - 1 ) ; } } int height ( Node node ) { if ( node == null ) return 0 ; else { int lheight = height ( node . left ) ; int rheight = height ( node . right ) ; if ( lheight > rheight ) return ( lheight + 1 ) ; else return ( rheight + 1 ) ; } } static public 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 ) ; Console . WriteLine ( " Level ▁ Order ▁ traversal ▁ " + " of ▁ binary ▁ tree ▁ is ▁ : ▁ " ) ; tree . reverseLevelOrder ( tree . root ) ; } }
Minimize the number of weakly connected nodes | C # code to minimize the number of weakly connected nodes ; Set of nodes which are traversed in each launch of the DFS ; Function traversing the graph using DFS approach and updating the set of nodes ; Building a undirected graph ; Computes the minimum number of disconnected components when a bi - directed graph is converted to a undirected graph ; Declaring and initializing a visited array ; We check if each node is visited once or not ; We only launch DFS from a node iff it is unvisited . ; Clearing the set of nodes on every relaunch of DFS ; Relaunching DFS from an unvisited node . ; Iterating over the node set to count the number of nodes visited after making the graph directed and storing it in the variable count . If count / 2 == number of nodes - 1 , then increment count by 1. ; Driver Code ; Building graph in the form of a adjacency list
using System ; using System . Collections ; using System . Collections . Generic ; class GFG { static HashSet < int > node = new HashSet < int > ( ) ; static List < int > [ ] Graph = new List < int > [ 10001 ] ; static void dfs ( bool [ ] visit , int src ) { visit [ src ] = true ; node . Add ( src ) ; int len = Graph [ src ] . Count ; for ( int i = 0 ; i < len ; i ++ ) if ( ! visit [ Graph [ src ] [ i ] ] ) dfs ( visit , Graph [ src ] [ i ] ) ; } static void buildGraph ( int [ ] x , int [ ] y , int len ) { for ( int i = 0 ; i < len ; i ++ ) { int p = x [ i ] ; int q = y [ i ] ; Graph [ p ] . Add ( q ) ; Graph [ q ] . Add ( p ) ; } } static int compute ( int n ) { bool [ ] visit = new bool [ n + 5 ] ; Array . Fill ( visit , false ) ; int number_of_nodes = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( ! visit [ i ] ) { node . Clear ( ) ; dfs ( visit , i ) ; int count = 0 ; foreach ( int it in node ) count += Graph [ ( it ) ] . Count ; count /= 2 ; if ( count == node . Count - 1 ) number_of_nodes ++ ; } } return number_of_nodes ; } static void Main ( string [ ] args ) { int n = 6 ; for ( int i = 0 ; i < 10001 ; i ++ ) { Graph [ i ] = new List < int > ( ) ; } int [ ] x = { 1 , 1 , 4 , 4 , 0 , 0 , 0 , 0 } ; int [ ] y = { 2 , 3 , 5 , 6 , 0 , 0 , 0 , 0 } ; buildGraph ( x , y , n ) ; Console . Write ( compute ( n ) + " ▁ weakly ▁ connected ▁ nodes " ) ; } }
Karp 's minimum mean (or average) weight cycle algorithm | C # program to find minimum average weight of a cycle in connected and directed graph . ; a struct to represent edges ; vector to store edges ; calculates the shortest path ; initializing all distances as - 1 ; shortest distance from first vertex to in tself consisting of 0 edges ; filling up the dp table ; Returns minimum value of average weight of a cycle in graph . ; array to store the avg values ; Compute average values for all vertices using weights of shortest paths store in dp . ; Find minimum value in avg [ ] ; Driver Code
using System ; using System . Collections . Generic ; class GFG { static int V = 4 ; public class Edge { public int from , weight ; public Edge ( int from , int weight ) { this . from = from ; this . weight = weight ; } } static List < Edge > [ ] edges = new List < Edge > [ V ] ; static void addedge ( int u , int v , int w ) { edges [ v ] . Add ( new Edge ( u , w ) ) ; } static void shortestpath ( int [ , ] dp ) { for ( int i = 0 ; i <= V ; i ++ ) for ( int j = 0 ; j < V ; j ++ ) dp [ i , j ] = - 1 ; dp [ 0 , 0 ] = 0 ; for ( int i = 1 ; i <= V ; i ++ ) { for ( int j = 0 ; j < V ; j ++ ) { for ( int k = 0 ; k < edges [ j ] . Count ; k ++ ) { if ( dp [ i - 1 , edges [ j ] [ k ] . from ] != - 1 ) { int curr_wt = dp [ i - 1 , edges [ j ] [ k ] . from ] + edges [ j ] [ k ] . weight ; if ( dp [ i , j ] == - 1 ) dp [ i , j ] = curr_wt ; else dp [ i , j ] = Math . Min ( dp [ i , j ] , curr_wt ) ; } } } } } static double minAvgWeight ( ) { int [ , ] dp = new int [ V + 1 , V ] ; shortestpath ( dp ) ; double [ ] avg = new double [ V ] ; for ( int i = 0 ; i < V ; i ++ ) avg [ i ] = - 1 ; for ( int i = 0 ; i < V ; i ++ ) { if ( dp [ V , i ] != - 1 ) { for ( int j = 0 ; j < V ; j ++ ) if ( dp [ j , i ] != - 1 ) avg [ i ] = Math . Max ( avg [ i ] , ( ( double ) dp [ V , i ] - dp [ j , i ] ) / ( V - j ) ) ; } } double result = avg [ 0 ] ; for ( int i = 0 ; i < V ; i ++ ) if ( avg [ i ] != - 1 && avg [ i ] < result ) result = avg [ i ] ; return result ; } public static void Main ( String [ ] args ) { for ( int i = 0 ; i < V ; i ++ ) edges [ i ] = new List < Edge > ( ) ; addedge ( 0 , 1 , 1 ) ; addedge ( 0 , 2 , 10 ) ; addedge ( 1 , 2 , 3 ) ; addedge ( 2 , 3 , 2 ) ; addedge ( 3 , 1 , 0 ) ; addedge ( 3 , 0 , 8 ) ; Console . Write ( " { 0 : F5 } " , minAvgWeight ( ) ) ; } }
Frequency of maximum occurring subsequence in given string | C # program for the above approach ; Function to find the frequency ; freq stores frequency of each english lowercase character ; dp [ i , j ] stores the count of subsequence with ' a ' + i and ' a ' + j character ; Increment the count of subsequence j and s [ i ] ; Update the frequency array ; For 1 length subsequence ; For 2 length subsequence ; Return the readonly result ; Driver Code ; Given String str ; Function call
using System ; class GFG { static int findCount ( String s ) { int [ ] freq = new int [ 26 ] ; int [ , ] dp = new int [ 26 , 26 ] ; for ( int i = 0 ; i < s . Length ; ++ i ) { for ( int j = 0 ; j < 26 ; j ++ ) { dp [ j , s [ i ] - ' a ' ] += freq [ j ] ; } freq [ s [ i ] - ' a ' ] ++ ; } int ans = 0 ; for ( int i = 0 ; i < 26 ; i ++ ) ans = Math . Max ( freq [ i ] , ans ) ; for ( int i = 0 ; i < 26 ; i ++ ) { for ( int j = 0 ; j < 26 ; j ++ ) { ans = Math . Max ( dp [ i , j ] , ans ) ; } } return ans ; } public static void Main ( String [ ] args ) { String str = " acbab " ; Console . Write ( findCount ( str ) ) ; } }
Create an array such that XOR of subarrays of length K is X | C # implementation to create an array in which the XOR of all elements of each contiguous sub - array of length K is X ; Function to construct the array ; Creating an array of size K , initialised with 0 ; Initialising the first element with the given XOR ; Driver code
using System ; class GFG { public static void constructArray ( int N , int K , int X ) { int [ ] ans = new int [ K ] ; ans [ 0 ] = X ; for ( int i = 0 ; i < N ; ++ i ) { Console . Write ( ans [ i % K ] + " ▁ " ) ; } } public static void Main ( string [ ] args ) { int N = 5 , K = 2 , X = 4 ; constructArray ( N , K , X ) ; } }
Two player game in which a player can remove all occurrences of a number | C # implementation for Two player game in which a player can remove all occurrences of a number ; Function that print whether player1 can wins or loses ; Storing the number of occurrence of elements in unordered map ; Variable to check if the occurrence of repeated elements is >= 4 and multiple of 2 or not ; Count elements which occur more than once ; Driver code
using System ; using System . Collections . Generic ; class GFG { public static void game ( int [ ] v , int n ) { Dictionary < int , int > m = new Dictionary < int , int > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( ! m . ContainsKey ( v [ i ] ) ) m . Add ( v [ i ] , 1 ) ; else m [ v [ i ] ] = m [ v [ i ] ] + 1 ; } int count = 0 ; int check = 0 ; foreach ( KeyValuePair < int , int > i in m ) { if ( i . Value > 1 ) { if ( i . Value >= 4 && i . Value % 2 == 0 ) check ++ ; count ++ ; } } bool flag ; if ( check % 2 != 0 ) flag = false ; if ( check % 2 != 0 ) Console . WriteLine ( " Yes " ) ; else if ( n % 2 == 0 && count % 2 == 0 ) Console . WriteLine ( " No " ) ; else Console . WriteLine ( " Yes " ) ; } public static void Main ( String [ ] args ) { int [ ] arr = { 3 , 2 , 2 , 3 , 3 , 5 } ; int size = arr . Length ; game ( arr , size ) ; } }
Count of elements which form a loop in an Array according to given constraints | C # program to number of elements which form a cycle in an array ; Function to count number of elements forming a cycle ; Array to store parent node of traversal . ; Array to determine whether current node is already counted in the cycle . ; Initialize the arrays . ; Check if current node is already traversed or not . If node is not traversed yet then parent value will be - 1. ; Traverse the graph until an already visited node is not found . ; Check parent value to ensure a cycle is present . ; Count number of nodes in the cycle . ; Driver code
using System ; class GFG { static int solve ( int [ ] A , int n ) { int i , cnt = 0 , j ; int [ ] parent = new int [ n ] ; int [ ] vis = new int [ n ] ; Array . Fill ( parent , - 1 ) ; Array . Fill ( vis , 0 ) ; for ( i = 0 ; i < n ; i ++ ) { j = i ; if ( parent [ j ] == - 1 ) { while ( parent [ j ] == - 1 ) { parent [ j ] = i ; j = __gcd ( j , A [ j ] ) % n ; } if ( parent [ j ] == i ) { while ( vis [ j ] == 0 ) { vis [ j ] = 1 ; cnt ++ ; j = __gcd ( j , A [ j ] ) % n ; } } } } return cnt ; } static int __gcd ( int a , int b ) { return b == 0 ? a : __gcd ( b , a % b ) ; } static void Main ( ) { int [ ] A = { 1 , 1 , 6 , 2 } ; int n = A . Length ; Console . WriteLine ( solve ( A , n ) ) ; } }
Find farthest node from each node in Tree | C # implementation to find the farthest node from each vertex of the tree ; Adjacency list to store edges ; Add edge between U and V in tree ; Edge from U to V ; Edge from V to U ; DFS to find the first End Node of diameter ; Calculating level of nodes ; Go in opposite direction of parent ; Function to clear the levels of the nodes ; Set all value of lvl [ ] to 0 for next dfs ; Set maximum with 0 ; DFS will calculate second end of the diameter ; Calculating level of nodes ; Store the node with maximum depth from end1 ; Go in opposite direction of parent ; Function to find the distance of the farthest distant node ; Storing distance from end1 to node u ; Function to find the distance of nodes from second end of diameter ; Storing distance from end2 to node u ; Joining Edge between two nodes of the tree ; Find the one end of the diameter of tree ; Find the other end of the diameter of tree ; Find the distance to each node from end1 ; Find the distance to each node from end2 ; Comparing distance between the two ends of diameter ; Driver Code ; Function call
using System ; using System . Collections . Generic ; class GFG { static int N = 10000 ; static List < int > [ ] adj = new List < int > [ N ] ; static int [ ] lvl = new int [ N ] , dist1 = new int [ N ] , dist2 = new int [ N ] ; static void AddEdge ( int u , int v ) { adj [ u ] . Add ( v ) ; adj [ v ] . Add ( u ) ; } static int end1 , end2 , maxi ; static void findFirstEnd ( int u , int p ) { lvl [ u ] = 1 + lvl [ p ] ; if ( lvl [ u ] > maxi ) { maxi = lvl [ u ] ; end1 = u ; } for ( int i = 0 ; i < adj [ u ] . Count ; i ++ ) { if ( adj [ u ] [ i ] != p ) { findFirstEnd ( adj [ u ] [ i ] , u ) ; } } } static void clear ( int n ) { for ( int i = 0 ; i <= n ; i ++ ) { lvl [ i ] = 0 ; } maxi = 0 ; dist1 [ 0 ] = dist2 [ 0 ] = - 1 ; } static void findSecondEnd ( int u , int p ) { lvl [ u ] = 1 + lvl [ p ] ; if ( lvl [ u ] > maxi ) { maxi = lvl [ u ] ; end2 = u ; } for ( int i = 0 ; i < adj [ u ] . Count ; i ++ ) { if ( adj [ u ] [ i ] != p ) { findSecondEnd ( adj [ u ] [ i ] , u ) ; } } } static void findDistancefromFirst ( int u , int p ) { dist1 [ u ] = 1 + dist1 [ p ] ; for ( int i = 0 ; i < adj [ u ] . Count ; i ++ ) { if ( adj [ u ] [ i ] != p ) { findDistancefromFirst ( adj [ u ] [ i ] , u ) ; } } } static void findDistancefromSecond ( int u , int p ) { dist2 [ u ] = 1 + dist2 [ p ] ; for ( int i = 0 ; i < adj [ u ] . Count ; i ++ ) { if ( adj [ u ] [ i ] != p ) { findDistancefromSecond ( adj [ u ] [ i ] , u ) ; } } } static void findNodes ( ) { int n = 5 ; AddEdge ( 1 , 2 ) ; AddEdge ( 1 , 3 ) ; AddEdge ( 3 , 4 ) ; AddEdge ( 3 , 5 ) ; findFirstEnd ( 1 , 0 ) ; clear ( n ) ; findSecondEnd ( end1 , 0 ) ; findDistancefromFirst ( end1 , 0 ) ; findDistancefromSecond ( end2 , 0 ) ; for ( int i = 1 ; i <= n ; i ++ ) { int x = dist1 [ i ] ; int y = dist2 [ i ] ; if ( x >= y ) { Console . Write ( end1 + " ▁ " ) ; } else { Console . Write ( end2 + " ▁ " ) ; } } } public static void Main ( String [ ] args ) { for ( int i = 0 ; i < N ; i ++ ) { adj [ i ] = new List < int > ( ) ; } findNodes ( ) ; } }
Sum and Product of all even digit sum Nodes of a Singly Linked List | C # program for the above approach ; Node of Linked List ; Function to insert a node at the beginning of the singly Linked List ; Allocate new node ; Insert the data ; Link old list to the new node ; Move head to point the new node ; Function to find the digit sum for a number ; Return the sum ; Function to find the required sum and product ; Initialise the sum and product to 0 and 1 respectively ; Traverse the given linked list ; If current node has even digit sum then include it in resultant sum and product ; Find the sum and the product ; Print the readonly Sum and Product ; Driver Code ; Head of the linked list ; Create the linked list 15.16 . 8.6 .13 ; Function call
using System ; class GFG { class Node { public int data ; public Node next ; } ; static Node push ( Node head_ref , int new_data ) { Node new_node = new Node ( ) ; new_node . data = new_data ; new_node . next = head_ref ; head_ref = new_node ; return head_ref ; } static int digitSum ( int num ) { int sum = 0 ; while ( num > 0 ) { sum += ( num % 10 ) ; num /= 10 ; } return sum ; } static void sumAndProduct ( Node head_ref ) { int prod = 1 ; int sum = 0 ; Node ptr = head_ref ; while ( ptr != null ) { if ( ( digitSum ( ptr . data ) % 2 != 1 ) ) { prod *= ptr . data ; sum += ptr . data ; } ptr = ptr . next ; } Console . Write ( " Sum ▁ = ▁ " + sum + " STRNEWLINE " ) ; Console . Write ( " Product ▁ = ▁ " + prod ) ; } public static void Main ( String [ ] args ) { Node head = null ; head = push ( head , 13 ) ; head = push ( head , 6 ) ; head = push ( head , 8 ) ; head = push ( head , 16 ) ; head = push ( head , 15 ) ; sumAndProduct ( head ) ; } }
Shortest Palindromic Substring | C # program to find the shortest palindromic substring ; Function return the shortest palindromic substring ; One by one consider every character as center point of even and length palindromes ; Find the longest odd length palindrome with center point as i ; Find the even length palindrome with center points as i - 1 and i . ; Smallest substring which is not empty ; Driver code
using System ; using System . Collections . Generic ; class GFG { static string ShortestPalindrome ( string s ) { int n = s . Length ; List < string > v = new List < string > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { int l = i ; int r = i ; string ans1 = " " ; string ans2 = " " ; while ( l >= 0 && r < n && s [ l ] == s [ r ] ) { ans1 += s [ l ] ; l -- ; r ++ ; } l = i - 1 ; r = i ; while ( l >= 0 && r < n && s [ l ] == s [ r ] ) { ans2 += s [ l ] ; l -- ; r ++ ; } v . Add ( ans1 ) ; v . Add ( ans2 ) ; } string ans = v [ 0 ] ; for ( int i = 0 ; i < v . Count ; i ++ ) { if ( v [ i ] != " " ) { if ( ans [ 0 ] >= v [ i ] [ 0 ] ) { ans = v [ i ] ; } } } return ans ; } static public void Main ( ) { string s = " geeksforgeeks " ; Console . WriteLine ( ShortestPalindrome ( s ) ) ; } }
Minimum increment or decrement operations required to make the array sorted | C # implementation of the approach ; Function to return the minimum number of given operations required to sort the array ; Number of elements in the array ; Smallest element in the array ; Largest element in the array ; dp ( i , j ) represents the minimum number of operations needed to make the array [ 0 . . i ] sorted in non - decreasing order given that ith element is j ; Fill the dp [ ] , array for base cases ; Using results for the first ( i - 1 ) elements , calculate the result for the ith element ; If the ith element is j then we can have any value from small to j for the i - 1 th element We choose the one that requires the minimum operations ; If we made the ( n - 1 ) th element equal to j we required dp ( n - 1 , j ) operations We choose the minimum among all possible dp ( n - 1 , j ) where j goes from small to large ; Driver code
using System ; using System . Linq ; using System . Collections . Generic ; class GFG { static int getMinimumOps ( List < int > ar ) { int n = ar . Count ; int small = ar . Min ( ) ; int large = ar . Max ( ) ; int [ , ] dp = new int [ n , large + 1 ] ; for ( int j = small ; j <= large ; j ++ ) { dp [ 0 , j ] = Math . Abs ( ar [ 0 ] - j ) ; } for ( int i = 1 ; i < n ; i ++ ) { int minimum = int . MaxValue ; for ( int j = small ; j <= large ; j ++ ) { minimum = Math . Min ( minimum , dp [ i - 1 , j ] ) ; dp [ i , j ] = minimum + Math . Abs ( ar [ i ] - j ) ; } } int ans = int . MaxValue ; for ( int j = small ; j <= large ; j ++ ) { ans = Math . Min ( ans , dp [ n - 1 , j ] ) ; } return ans ; } public static void Main ( String [ ] args ) { int [ ] arr = { 1 , 2 , 1 , 4 , 3 } ; List < int > ar = new List < int > ( arr ) ; Console . WriteLine ( getMinimumOps ( ar ) ) ; } }