content
stringlengths
219
31.2k
complexity
stringclasses
5 values
file_name
stringlengths
6
9
complexity_ranked
float64
0.1
0.9
class SubarraySum { /* Returns true if the there is a subarray of arr[] with a sum equal to 'sum' otherwise returns false. Also, prints the result */ int subArraySum( int arr[], int n, int sum) { int curr_sum, i, j; // Pick a starting point for (i = 0 ; i < n; i++) { curr_sum = arr[i]; // try all subarrays starting with 'i' for (j = i + 1 ; j <= n; j++) { if (curr_sum == sum) { int p = j - 1 ; System.out.println( "Sum found between indexes " + i + " and " + p); return 1 ; } if (curr_sum > sum || j == n) break ; curr_sum = curr_sum + arr[j]; } } System.out.println( "No subarray found" ); return 0 ; } public static void main(String[] args) { SubarraySum arraysum = new SubarraySum(); int arr[] = { 15 , 2 , 4 , 8 , 9 , 5 , 10 , 23 }; int n = arr.length; int sum = 23 ; arraysum.subArraySum(arr, n, sum); } } // This code has been contributed by Mayank Jaiswal(mayank_24)
n_square
133.java
0.9
// Java program to find a triplet class FindTriplet { // returns true if there is triplet with sum equal // to 'sum' present in A[]. Also, prints the triplet boolean find3Numbers( int A[], int arr_size, int sum) { int l, r; /* Sort the elements */ quickSort(A, 0 , arr_size - 1 ); /* Now fix the first element one by one and find the other two elements */ for ( int i = 0 ; i < arr_size - 2 ; i++) { // To find the other two elements, start two index variables // from two corners of the array and move them toward each // other l = i + 1 ; // index of the first element in the remaining elements r = arr_size - 1 ; // index of the last element while (l < r) { if (A[i] + A[l] + A[r] == sum) { System.out.print( "Triplet is " + A[i] + ", " + A[l] + ", " + A[r]); return true ; } else if (A[i] + A[l] + A[r] < sum) l++; else // A[i] + A[l] + A[r] > sum r--; } } // If we reach here, then no triplet was found return false ; } int partition( int A[], int si, int ei) { int x = A[ei]; int i = (si - 1 ); int j; for (j = si; j <= ei - 1 ; j++) { if (A[j] <= x) { i++; int temp = A[i]; A[i] = A[j]; A[j] = temp; } } int temp = A[i + 1 ]; A[i + 1 ] = A[ei]; A[ei] = temp; return (i + 1 ); } /* Implementation of Quick Sort A[] --> Array to be sorted si --> Starting index ei --> Ending index */ void quickSort( int A[], int si, int ei) { int pi; /* Partitioning index */ if (si < ei) { pi = partition(A, si, ei); quickSort(A, si, pi - 1 ); quickSort(A, pi + 1 , ei); } } // Driver program to test above functions public static void main(String[] args) { FindTriplet triplet = new FindTriplet(); int A[] = { 1 , 4 , 45 , 6 , 10 , 8 }; int sum = 22 ; int arr_size = A.length; triplet.find3Numbers(A, arr_size, sum); } }
n_square
140.java
0.9
// Java program to find triplets in a given // array whose sum is zero import java.util.*; class GFG { // function to print triplets with 0 sum static void findTriplets( int arr[], int n) { boolean found = false ; for ( int i = 0 ; i < n - 1 ; i++) { // Find all pairs with sum equals to // "-arr[i]" HashSet<Integer> s = new HashSet<Integer>(); for ( int j = i + 1 ; j < n; j++) { int x = -(arr[i] + arr[j]); if (s.contains(x)) { System.out.printf( "%d %d %d\n" , x, arr[i], arr[j]); found = true ; } else { s.add(arr[j]); } } } if (found == false ) { System.out.printf( " No Triplet Found\n" ); } } // Driver code public static void main(String[] args) { int arr[] = { 0 , - 1 , 2 , - 3 , 1 }; int n = arr.length; findTriplets(arr, n); } } // This code contributed by Rajput-Ji
n_square
143.java
0.9
// Java program to print a given matrix in spiral form import java.io.*; class GFG { // Function print matrix in spiral form static void spiralPrint( int m, int n, int a[][]) { int i, k = 0 , l = 0 ; /* k - starting row index m - ending row index l - starting column index n - ending column index i - iterator */ while (k < m && l < n) { // Print the first row from the remaining rows for (i = l; i < n; ++i) { System.out.print(a[k][i] + " " ); } k++; // Print the last column from the remaining columns for (i = k; i < m; ++i) { System.out.print(a[i][n - 1 ] + " " ); } n--; // Print the last row from the remaining rows */ if (k < m) { for (i = n - 1 ; i >= l; --i) { System.out.print(a[m - 1 ][i] + " " ); } m--; } // Print the first column from the remaining columns */ if (l < n) { for (i = m - 1 ; i >= k; --i) { System.out.print(a[i][l] + " " ); } l++; } } } // driver program public static void main(String[] args) { int R = 3 ; int C = 6 ; int a[][] = { { 1 , 2 , 3 , 4 , 5 , 6 }, { 7 , 8 , 9 , 10 , 11 , 12 }, { 13 , 14 , 15 , 16 , 17 , 18 } }; spiralPrint(R, C, a); } } // Contributed by Pramod Kumar
n_square
147.java
0.9
// Java implementation to print // the counter clock wise // spiral traversal of matrix import java.io.*; class GFG { static int R = 4 ; static int C = 4 ; // function to print the // required traversal static void counterClockspiralPrint( int m, int n, int arr[][]) { int i, k = 0 , l = 0 ; /* k - starting row index m - ending row index l - starting column index n - ending column index i - iterator */ // initialize the count int cnt = 0 ; // total number of // elements in matrix int total = m * n; while (k < m && l < n) { if (cnt == total) break ; // Print the first column // from the remaining columns for (i = k; i < m; ++i) { System.out.print(arr[i][l] + " " ); cnt++; } l++; if (cnt == total) break ; // Print the last row from // the remaining rows for (i = l; i < n; ++i) { System.out.print(arr[m - 1 ][i] + " " ); cnt++; } m--; if (cnt == total) break ; // Print the last column // from the remaining columns if (k < m) { for (i = m - 1 ; i >= k; --i) { System.out.print(arr[i][n - 1 ] + " " ); cnt++; } n--; } if (cnt == total) break ; // Print the first row // from the remaining rows if (l < n) { for (i = n - 1 ; i >= l; --i) { System.out.print(arr[k][i] + " " ); cnt++; } k++; } } } // Driver Code public static void main(String[] args) { int arr[][] = { { 1 , 2 , 3 , 4 }, { 5 , 6 , 7 , 8 }, { 9 , 10 , 11 , 12 }, { 13 , 14 , 15 , 16 } }; // Function calling counterClockspiralPrint(R, C, arr); } } // This code is contributed by vt_m
n_square
148.java
0.9
// Java prorgam for finding max path in matrix import static java.lang.Math.max; class GFG { public static int N = 4 , M = 6 ; // Function to calculate max path in matrix static int findMaxPath( int mat[][]) { // To find max val in first row int res = - 1 ; for ( int i = 0 ; i < M; i++) res = max(res, mat[ 0 ][i]); for ( int i = 1 ; i < N; i++) { res = - 1 ; for ( int j = 0 ; j < M; j++) { // When all paths are possible if (j > 0 && j < M - 1 ) mat[i][j] += max(mat[i - 1 ][j], max(mat[i - 1 ][j - 1 ], mat[i - 1 ][j + 1 ])); // When diagonal right is not possible else if (j > 0 ) mat[i][j] += max(mat[i - 1 ][j], mat[i - 1 ][j - 1 ]); // When diagonal left is not possible else if (j < M - 1 ) mat[i][j] += max(mat[i - 1 ][j], mat[i - 1 ][j + 1 ]); // Store max path sum res = max(mat[i][j], res); } } return res; } // driver program public static void main (String[] args) { int mat[][] = { { 10 , 10 , 2 , 0 , 20 , 4 }, { 1 , 0 , 0 , 30 , 2 , 5 }, { 0 , 10 , 4 , 0 , 2 , 0 }, { 1 , 0 , 2 , 20 , 0 , 4 } }; System.out.println(findMaxPath(mat)); } } // Contributed by Pramod Kumar
n_square
149.java
0.9
// Java program to remove duplicates from unsorted // linked list class LinkedList { static Node head; static class Node { int data; Node next; Node( int d) { data = d; next = null ; } } /* Function to remove duplicates from an unsorted linked list */ void remove_duplicates() { Node ptr1 = null , ptr2 = null , dup = null ; ptr1 = head; /* Pick elements one by one */ while (ptr1 != null && ptr1.next != null ) { ptr2 = ptr1; /* Compare the picked element with rest of the elements */ while (ptr2.next != null ) { /* If duplicate then delete it */ if (ptr1.data == ptr2.next.data) { /* sequence of steps is important here */ dup = ptr2.next; ptr2.next = ptr2.next.next; System.gc(); } else /* This is tricky */ { ptr2 = ptr2.next; } } ptr1 = ptr1.next; } } void printList(Node node) { while (node != null ) { System.out.print(node.data + " " ); node = node.next; } } public static void main(String[] args) { LinkedList list = new LinkedList(); list.head = new Node( 10 ); list.head.next = new Node( 12 ); list.head.next.next = new Node( 11 ); list.head.next.next.next = new Node( 11 ); list.head.next.next.next.next = new Node( 12 ); list.head.next.next.next.next.next = new Node( 11 ); list.head.next.next.next.next.next.next = new Node( 10 ); System.out.println( "Linked List before removing duplicates : \n " ); list.printList(head); list.remove_duplicates(); System.out.println( "" ); System.out.println( "Linked List after removing duplicates : \n " ); list.printList(head); } } // This code has been contributed by Mayank Jaiswal
n_square
162.java
0.9
// Java Code to find the last man Standing public class GFG { // Node class to store data static class Node { public int data ; public Node next; public Node( int data ) { this .data = data; } } /* Function to find the only person left after one in every m-th node is killed in a circle of n nodes */ static void getJosephusPosition( int m, int n) { // Create a circular linked list of // size N. Node head = new Node( 1 ); Node prev = head; for ( int i = 2 ; i <= n; i++) { prev.next = new Node(i); prev = prev.next; } // Connect last node to first prev.next = head; /* while only one node is left in the linked list*/ Node ptr1 = head, ptr2 = head; while (ptr1.next != ptr1) { // Find m-th node int count = 1 ; while (count != m) { ptr2 = ptr1; ptr1 = ptr1.next; count++; } /* Remove the m-th node */ ptr2.next = ptr1.next; ptr1 = ptr2.next; } System.out.println ( "Last person left standing " + "(Josephus Position) is " + ptr1.data); } /* Driver program to test above functions */ public static void main(String args[]) { int n = 14 , m = 2 ; getJosephusPosition(m, n); } }
n_square
171.java
0.9
// A Naive Java program to find // maximum sum rotation import java.util.*; import java.io.*; class GFG { // Returns maximum value of i*arr[i] static int maxSum( int arr[], int n) { // Initialize result int res = Integer.MIN_VALUE; // Consider rotation beginning with i // for all possible values of i. for ( int i = 0 ; i < n; i++) { // Initialize sum of current rotation int curr_sum = 0 ; // Compute sum of all values. We don't // actually rotation the array, but compute // sum by finding ndexes when arr[i] is // first element for ( int j = 0 ; j < n; j++) { int index = (i + j) % n; curr_sum += j * arr[index]; } // Update result if required res = Math.max(res, curr_sum); } return res; } // Driver code public static void main(String args[]) { int arr[] = { 8 , 3 , 1 , 2 }; int n = arr.length; System.out.println(maxSum(arr, n)); } } // This code is contributed by Sahil_Bansall
n_square
18.java
0.9
// Java implementation for brute force method to calculate stock span values import java.util.Arrays; class GFG { // method to calculate stock span values static void calculateSpan( int price[], int n, int S[]) { // Span value of first day is always 1 S[ 0 ] = 1 ; // Calculate span value of remaining days by linearly checking // previous days for ( int i = 1 ; i < n; i++) { S[i] = 1 ; // Initialize span value // Traverse left while the next element on left is smaller // than price[i] for ( int j = i - 1 ; (j >= 0 ) && (price[i] >= price[j]); j--) S[i]++; } } // A utility function to print elements of array static void printArray( int arr[]) { System.out.print(Arrays.toString(arr)); } // Driver program to test above functions public static void main(String[] args) { int price[] = { 10 , 4 , 5 , 90 , 120 , 80 }; int n = price.length; int S[] = new int [n]; // Fill the span values in array S[] calculateSpan(price, n, S); // print the calculated span values printArray(S); } } // This code is contributed by Sumit Ghosh
n_square
186.java
0.9
// Java program to sort an // array using stack import java.io.*; import java.util.*; class GFG { // This function return // the sorted stack static Stack<Integer> sortStack(Stack<Integer> input) { Stack<Integer> tmpStack = new Stack<Integer>(); while (!input.empty()) { // pop out the // first element int tmp = input.peek(); input.pop(); // while temporary stack is // not empty and top of stack // is smaller than temp while (!tmpStack.empty() && tmpStack.peek() < tmp) { // pop from temporary // stack and push it // to the input stack input.push(tmpStack.peek()); tmpStack.pop(); } // push temp in // tempory of stack tmpStack.push(tmp); } return tmpStack; } static void sortArrayUsingStacks( int []arr, int n) { // push array elements // to stack Stack<Integer> input = new Stack<Integer>(); for ( int i = 0 ; i < n; i++) input.push(arr[i]); // Sort the temporary stack Stack<Integer> tmpStack = sortStack(input); // Put stack elements // in arrp[] for ( int i = 0 ; i < n; i++) { arr[i] = tmpStack.peek(); tmpStack.pop(); } } // Driver Code public static void main(String args[]) { int []arr = { 10 , 5 , 15 , 45 }; int n = arr.length; sortArrayUsingStacks(arr, n); for ( int i = 0 ; i < n; i++) System.out.print(arr[i] + " " ); } } // This code is contributed by // Manish Shaw(manishshaw1)
n_square
199.java
0.9
// Java program to implement sorting a // queue data structure import java.util.LinkedList; import java.util.Queue; class GFG { // Queue elements after sortIndex are // already sorted. This function returns // index of minimum element from front to // sortIndex public static int minIndex(Queue<Integer> list, int sortIndex) { int min_index = - 1 ; int min_value = Integer.MAX_VALUE; int s = list.size(); for ( int i = 0 ; i < s; i++) { int current = list.peek(); // This is dequeue() in Java STL list.poll(); // we add the condition i <= sortIndex // because we don't want to traverse // on the sorted part of the queue, // which is the right part. if (current <= min_value && i <= sortIndex) { min_index = i; min_value = current; } list.add(current); } return min_index; } // Moves given minimum element // to rear of queue public static void insertMinToRear(Queue<Integer> list, int min_index) { int min_value = 0 ; int s = list.size(); for ( int i = 0 ; i < s; i++) { int current = list.peek(); list.poll(); if (i != min_index) list.add(current); else min_value = current; } list.add(min_value); } public static void sortQueue(Queue<Integer> list) { for ( int i = 1 ; i <= list.size(); i++) { int min_index = minIndex(list,list.size() - i); insertMinToRear(list, min_index); } } //Driver function public static void main (String[] args) { Queue<Integer> list = new LinkedList<Integer>(); list.add( 30 ); list.add( 11 ); list.add( 15 ); list.add( 4 ); //Sort Queue sortQueue(list); //print sorted Queue while (list.isEmpty()== false ) { System.out.print(list.peek() + " " ); list.poll(); } } } // This code is contributed by akash1295
n_square
226.java
0.9
// Java program for recursive level order traversal in spiral form /* A binary tree node has data, pointer to left child and a pointer to right child */ class Node { int data; Node left, right; public Node( int d) { data = d; left = right = null ; } } class BinaryTree { Node root; // Function to print the spiral traversal of tree void printSpiral(Node node) { int h = height(node); int i; /* ltr -> left to right. If this variable is set then the given label is traversed from left to right */ boolean ltr = false ; for (i = 1 ; i <= h; i++) { printGivenLevel(node, i, ltr); /*Revert ltr to traverse next level in opposite order*/ ltr = !ltr; } } /* Compute the "height" of a tree -- the number of nodes along the longest path from the root node down to the farthest leaf node.*/ int height(Node node) { if (node == null ) return 0 ; else { /* compute the height of each subtree */ int lheight = height(node.left); int rheight = height(node.right); /* use the larger one */ if (lheight > rheight) return (lheight + 1 ); else return (rheight + 1 ); } } /* Print nodes at a given level */ void printGivenLevel(Node node, int level, boolean ltr) { if (node == null ) return ; if (level == 1 ) System.out.print(node.data + " " ); else if (level > 1 ) { if (ltr != false ) { printGivenLevel(node.left, level - 1 , ltr); printGivenLevel(node.right, level - 1 , ltr); } else { printGivenLevel(node.right, level - 1 , ltr); printGivenLevel(node.left, level - 1 , ltr); } } } /* Driver program to test the above functions */ 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( 7 ); tree.root.left.right = new Node( 6 ); tree.root.right.left = new Node( 5 ); tree.root.right.right = new Node( 4 ); System.out.println( "Spiral order traversal of Binary Tree is " ); tree.printSpiral(tree.root); } } // This code has been contributed by Mayank Jaiswal(mayank_24)
n_square
227.java
0.9
// Java Program to find the maximum for each and every contiguous subarray of size k. public class GFG { // Method to find the maximum for each and every contiguous subarray of size k. static void printKMax( int arr[], int n, int k) { int j, max; for ( int i = 0 ; i <= n - k; i++) { max = arr[i]; for (j = 1 ; j < k; j++) { if (arr[i + j] > max) max = arr[i + j]; } System.out.print(max + " " ); } } // Driver method public static void main(String args[]) { int arr[] = { 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 }; int k = 3 ; printKMax(arr, arr.length, k); } } // This code is contributed by Sumit Ghosh
n_square
229.java
0.9
// Java implementation to find the first negative // integer in every window of size k import java.util.*; class solution { // function to find the first negative // integer in every window of size k static void printFirstNegativeInteger( int arr[], int n, int k) { // flag to check whether window contains // a negative integer or not boolean flag; // Loop for each subarray(window) of size k for ( int i = 0 ; i<(n-k+ 1 ); i++) { flag = false ; // traverse through the current window for ( int j = 0 ; j<k; j++) { // if a negative integer is found, then // it is the first negative integer for // current window. Print it, set the flag // and break if (arr[i+j] < 0 ) { System.out.print((arr[i+j])+ " " ); flag = true ; break ; } } // if the current window does not // contain a negative integer if (!flag) System.out.print( "0" + " " ); } } // Driver program to test above functions public static void main(String args[]) { int arr[] = { 12 , - 1 , - 7 , 8 , - 15 , 30 , 16 , 28 }; int n = arr.length; int k = 3 ; printFirstNegativeInteger(arr, n, k); } } // This code is contributed by // Shashank_Sharma
n_square
237.java
0.9
// A simple Java program to find max subarray XOR class GFG { static int maxSubarrayXOR( int arr[], int n) { int ans = Integer.MIN_VALUE; // Initialize result // Pick starting points of subarrays for ( int i= 0 ; i<n; i++) { // to store xor of current subarray int curr_xor = 0 ; // Pick ending points of subarrays starting with i for ( int j=i; j<n; j++) { curr_xor = curr_xor ^ arr[j]; ans = Math.max(ans, curr_xor); } } return ans; } // Driver program to test above functions public static void main(String args[]) { int arr[] = { 8 , 1 , 2 , 12 }; int n = arr.length; System.out.println( "Max subarray XOR is " + maxSubarrayXOR(arr, n)); } } //This code is contributed by Sumit Ghosh
n_square
249.java
0.9
// Java program to split array and move first // part to end. import java.util.*; import java.lang.*; class GFG { public static void splitArr( int arr[], int n, int k) { for ( int i = 0 ; i < k; i++) { // Rotate array by 1. int x = arr[ 0 ]; for ( int j = 0 ; j < n - 1 ; ++j) arr[j] = arr[j + 1 ]; arr[n - 1 ] = x; } } // Driver code public static void main(String[] args) { int arr[] = { 12 , 10 , 5 , 6 , 52 , 36 }; int n = arr.length; int position = 2 ; splitArr(arr, 6 , position); for ( int i = 0 ; i < n; ++i) System.out.print(arr[i] + " " ); } } // Code Contributed by Mohit Gupta_OMG <(0_o)>
n_square
25.java
0.9
// Java program to CountKSubStr number of substrings // with exactly distinct characters in a given string import java.util.Arrays; public class CountKSubStr { // Function to count number of substrings // with exactly k unique characters int countkDist(String str, int k) { // Initialize result int res = 0 ; int n = str.length(); // To store count of characters from 'a' to 'z' int cnt[] = new int [ 26 ]; // Consider all substrings beginning with // str[i] for ( int i = 0 ; i < n; i++) { int dist_count = 0 ; // Initializing count array with 0 Arrays.fill(cnt, 0 ); // Consider all substrings between str[i..j] for ( int j=i; j<n; j++) { // If this is a new character for this // substring, increment dist_count. if (cnt[str.charAt(j) - 'a' ] == 0 ) dist_count++; // Increment count of current character cnt[str.charAt(j) - 'a' ]++; // If distinct character count becomes k, // then increment result. if (dist_count == k) res++; } } return res; } // Driver Program public static void main(String[] args) { CountKSubStr ob = new CountKSubStr(); String ch = "abcbaa" ; int k = 3 ; System.out.println( "Total substrings with exactly " + k + " distinct characters : " + ob.countkDist(ch, k)); } }
n_square
251.java
0.9
// Java program to count number of substrings // with counts of distinct characters as k. class GFG { static int MAX_CHAR = 26 ; // Returns true if all values // in freq[] are either 0 or k. static boolean check( int freq[], int k) { for ( int i = 0 ; i < MAX_CHAR; i++) if (freq[i] != 0 && freq[i] != k) return false ; return true ; } // Returns count of substrings where frequency // of every present character is k static int substrings(String s, int k) { int res = 0 ; // Initialize result // Pick a starting point for ( int i = 0 ; i< s.length(); i++) { // Initialize all frequencies as 0 // for this starting point int freq[] = new int [MAX_CHAR]; // One by one pick ending points for ( int j = i; j<s.length(); j++) { // Increment frequency of current char int index = s.charAt(j) - 'a' ; freq[index]++; // If frequency becomes more than // k, we can't have more substrings // starting with i if (freq[index] > k) break ; // If frequency becomes k, then check // other frequencies as well. else if (freq[index] == k && check(freq, k) == true ) res++; } } return res; } // Driver code public static void main(String[] args) { String s = "aabbcc" ; int k = 2 ; System.out.println(substrings(s, k)); s = "aabbc" ; k = 2 ; System.out.println(substrings(s, k)); } } // This code has been contributed by 29AjayKumar
n_square
252.java
0.9
// Java program to count number of substrings // of a string import java.io.*; public class GFG { static int countNonEmptySubstr(String str) { int n = str.length(); return n * (n + 1 ) / 2 ; } // Driver code public static void main(String args[]) { String s = "abcde" ; System.out.println( countNonEmptySubstr(s)); } } // This code is contributed // by Manish Shaw (manishshaw1)
n_square
254.java
0.9
// Java program to count all substrings with same // first and last characters. public class GFG { // Returns true if first and last characters // of s are same. static boolean checkEquality(String s) { return (s.charAt( 0 ) == s.charAt(s.length() - 1 )); } static int countSubstringWithEqualEnds(String s) { int result = 0 ; int n = s.length(); // Starting point of substring for ( int i = 0 ; i < n; i++) // Length of substring for ( int len = 1 ; len <= n-i; len++) // Check if current substring has same // starting and ending characters. if (checkEquality(s.substring(i, i + len))) result++; return result; } // Driver function public static void main(String args[]) { String s = "abcab" ; System.out.println(countSubstringWithEqualEnds(s)); } } // This code is contributed by Sumit Ghosh
n_square
257.java
0.9
// Space efficient Java program to count all // substrings with same first and last characters. public class GFG { static int countSubstringWithEqualEnds(String s) { int result = 0 ; int n = s.length(); // Iterating through all substrings in // way so that we can find first and last // character easily for ( int i = 0 ; i < n; i++) for ( int j = i; j < n; j++) if (s.charAt(i) == s.charAt(j)) result++; return result; } // Driver function public static void main(String args[]) { String s = "abcab" ; System.out.println(countSubstringWithEqualEnds(s)); } } // This code is contributed by Sumit Ghosh
n_square
258.java
0.9
// Java program to split array and move first // part to end. import java.util.*; import java.lang.*; class GFG { // Function to spilt array and // move first part to end public static void SplitAndAdd( int [] A, int length, int rotation){ //make a temporary array with double the size int [] tmp = new int [length* 2 ]; // copy array element in to new array twice System.arraycopy(A, 0 , tmp, 0 , length); System.arraycopy(A, 0 , tmp, length, length); for ( int i=rotation;i<rotation+length;i++) A[i-rotation]=tmp[i]; } // Driver code public static void main(String[] args) { int arr[] = { 12 , 10 , 5 , 6 , 52 , 36 }; int n = arr.length; int position = 2 ; SplitAndAdd(arr, n, position); for ( int i = 0 ; i < n; ++i) System.out.print(arr[i] + " " ); } }
n_square
26.java
0.9
// Java program to print all words that have // the same unique character set import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Map.Entry; public class GFG { static final int MAX_CHAR = 26 ; // Generates a key from given string. The key // contains all unique characters of given string // in sorted order consisting of only distinct elements. static String getKey(String str) { boolean [] visited = new boolean [MAX_CHAR]; Arrays.fill(visited, false ); // store all unique characters of current // word in key for ( int j = 0 ; j < str.length(); j++) visited[str.charAt(j) - 'a' ] = true ; String key = "" ; for ( int j= 0 ; j < MAX_CHAR; j++) if (visited[j]) key = key + ( char )( 'a' +j); return key; } // Print all words together with same character sets. static void wordsWithSameCharSet(String words[], int n) { // Stores indexes of all words that have same // set of unique characters. //unordered_map <string, vector <int> > Hash; HashMap<String, ArrayList<Integer>> Hash = new HashMap<>(); // Traverse all words for ( int i= 0 ; i<n; i++) { String key = getKey(words[i]); // if the key is already in the map // then get its corresponding value // and update the list and put it in the map if (Hash.containsKey(key)) { ArrayList<Integer> get_al = Hash.get(key); get_al.add(i); Hash.put(key, get_al); } // if key is not present in the map // then create a new list and add // both key and the list else { ArrayList<Integer> new_al = new ArrayList<>(); new_al.add(i); Hash.put(key, new_al); } } // print all words that have the same unique character set for (Entry<String, ArrayList<Integer>> it : Hash.entrySet()) { ArrayList<Integer> get =it.getValue(); for (Integer v:get) System.out.print( words[v] + ", " ); System.out.println(); } } // Driver program to test above function public static void main(String args[]) { String words[] = { "may" , "student" , "students" , "dog" , "studentssess" , "god" , "cat" , "act" , "tab" , "bat" , "flow" , "wolf" , "lambs" , "amy" , "yam" , "balms" , "looped" , "poodle" }; int n = words.length; wordsWithSameCharSet(words, n); } } // This code is contributed by Sumit Ghosh
n_square
264.java
0.9
// A simple C++ program to count number of //substrings starting and ending with 1 class CountSubString { int countSubStr( char str[], int n) { int res = 0 ; // Initialize result // Pick a starting point for ( int i = 0 ; i<n; i++) { if (str[i] == '1' ) { // Search for all possible ending point for ( int j = i + 1 ; j< n; j++) { if (str[j] == '1' ) res++; } } } return res; } // Driver program to test the above function public static void main(String[] args) { CountSubString count = new CountSubString(); String string = "00100101" ; char str[] = string.toCharArray(); int n = str.length; System.out.println(count.countSubStr(str,n)); } }
n_square
271.java
0.9
// Java implementation to find the character in // first string that is present at minimum index // in second string public class GFG { // method to find the minimum index character static void printMinIndexChar(String str, String patt) { // to store the index of character having // minimum index int minIndex = Integer.MAX_VALUE; // lengths of the two strings int m = str.length(); int n = patt.length(); // traverse 'patt' for ( int i = 0 ; i < n; i++) { // for each character of 'patt' traverse 'str' for ( int j = 0 ; j < m; j++) { // if patt.charAt(i)is found in 'str', check if // it has the minimum index or not. If yes, // then update 'minIndex' and break if (patt.charAt(i)== str.charAt(j) && j < minIndex) { minIndex = j; break ; } } } // print the minimum index character if (minIndex != Integer.MAX_VALUE) System.out.println( "Minimum Index Character = " + str.charAt(minIndex)); // if no character of 'patt' is present in 'str' else System.out.println( "No character present" ); } // Driver Method public static void main(String[] args) { String str = "geeksforgeeks" ; String patt = "set" ; printMinIndexChar(str, patt); } }
n_square
274.java
0.9
// A Simple Java program to find pairs with distance // equal to English alphabet distance class Test { // Method to count pairs static int countPairs(String str) { int result = 0 ; int n = str.length(); for ( int i = 0 ; i < n; i++) for ( int j = i + 1 ; j < n; j++) // Increment count if characters // are at same distance if (Math.abs(str.charAt(i) - str.charAt(j)) == Math.abs(i - j)) result++; return result; } // Driver method public static void main(String args[]) { String str = "geeksforgeeks" ; System.out.println(countPairs(str)); } }
n_square
278.java
0.9
// Java program to count number of times // S appears as a subsequence in T import java.io.*; class GFG { static int findSubsequenceCount(String S, String T) { int m = T.length(); int n = S.length(); // T can't appear as a subsequence in S if (m > n) return 0 ; // mat[i][j] stores the count of // occurrences of T(1..i) in S(1..j). int mat[][] = new int [m + 1 ][n + 1 ]; // Initializing first column with // all 0s. An emptystring can't have // another string as suhsequence for ( int i = 1 ; i <= m; i++) mat[i][ 0 ] = 0 ; // Initializing first row with all 1s. // An empty string is subsequence of all. for ( int j = 0 ; j <= n; j++) mat[ 0 ][j] = 1 ; // Fill mat[][] in bottom up manner for ( int i = 1 ; i <= m; i++) { for ( int j = 1 ; j <= n; j++) { // If last characters don't match, // then value is same as the value // without last character in S. if (T.charAt(i - 1 ) != S.charAt(j - 1 )) mat[i][j] = mat[i][j - 1 ]; // Else value is obtained considering two cases. // a) All substrings without last character in S // b) All substrings without last characters in // both. else mat[i][j] = mat[i][j - 1 ] + mat[i - 1 ][j - 1 ]; } } /* uncomment this to print matrix mat for (int i = 1; i <= m; i++, cout << endl) for (int j = 1; j <= n; j++) System.out.println ( mat[i][j] +" "); */ return mat[m][n]; } // Driver code to check above method public static void main(String[] args) { String T = "ge" ; String S = "geeksforgeeks" ; System.out.println(findSubsequenceCount(S, T)); } } // This code is contributed by vt_m
n_square
285.java
0.9
// Java program to find n'th Bell number import java.io.*; class GFG { // Function to find n'th Bell Number static int bellNumber( int n) { int [][] bell = new int [n+ 1 ][n+ 1 ]; bell[ 0 ][ 0 ] = 1 ; for ( int i= 1 ; i<=n; i++) { // Explicitly fill for j = 0 bell[i][ 0 ] = bell[i- 1 ][i- 1 ]; // Fill for remaining values of j for ( int j= 1 ; j<=i; j++) bell[i][j] = bell[i- 1 ][j- 1 ] + bell[i][j- 1 ]; } return bell[n][ 0 ]; } // Driver program public static void main (String[] args) { for ( int n= 0 ; n<= 5 ; n++) System.out.println( "Bell Number " + n + " is " +bellNumber(n)); } } // This code is contributed by Pramod Kumar
n_square
288.java
0.9
class GFG{ // A dynamic programming based function to find nth // Catalan number static int catalanDP( int n) { // Table to store results of subproblems int catalan[] = new int [n + 2 ]; // Initialize first two values in table catalan[ 0 ] = 1 ; catalan[ 1 ] = 1 ; // Fill entries in catalan[] using recursive formula for ( int i = 2 ; i <= n; i++) { catalan[i] = 0 ; for ( int j = 0 ; j < i; j++) { catalan[i] += catalan[j] * catalan[i - j - 1 ]; } } // Return last entry return catalan[n]; } // Driver code public static void main(String[] args) { for ( int i = 0 ; i < 10 ; i++) { System.out.print(catalanDP(i) + " " ); } } } // This code contributed by Rajput-Ji
n_square
290.java
0.9
// A Dynamic Programming based solution that uses table C[][] to // calculate the Binomial Coefficient class BinomialCoefficient { // Returns value of Binomial Coefficient C(n, k) static int binomialCoeff( int n, int k) { int C[][] = new int [n+ 1 ][k+ 1 ]; int i, j; // Calculate value of Binomial Coefficient in bottom up manner for (i = 0 ; i <= n; i++) { for (j = 0 ; j <= min(i, k); j++) { // Base Cases if (j == 0 || j == i) C[i][j] = 1 ; // Calculate value using previously stored values else C[i][j] = C[i- 1 ][j- 1 ] + C[i- 1 ][j]; } } return C[n][k]; } // A utility function to return minimum of two integers static int min( int a, int b) { return (a<b)? a: b; } /* Driver program to test above function*/ public static void main(String args[]) { int n = 5 , k = 2 ; System.out.println( "Value of C(" +n+ "," +k+ ") is " +binomialCoeff(n, k)); } } /*This code is contributed by Rajat Mishra*/
n_square
293.java
0.9
// Java code for Dynamic Programming based // solution that uses table P[][] to // calculate the Permutation Coefficient import java.io.*; import java.math.*; class GFG { // Returns value of Permutation // Coefficient P(n, k) static int permutationCoeff( int n, int k) { int P[][] = new int [n + 2 ][k + 2 ]; // Caculate value of Permutation // Coefficient in bottom up manner for ( int i = 0 ; i <= n; i++) { for ( int j = 0 ; j <= Math.min(i, k); j++) { // Base Cases if (j == 0 ) P[i][j] = 1 ; // Calculate value using previosly // stored values else P[i][j] = P[i - 1 ][j] + (j * P[i - 1 ][j - 1 ]); // This step is important // as P(i,j)=0 for j>i P[i][j + 1 ] = 0 ; } } return P[n][k]; } // Driver Code public static void main(String args[]) { int n = 10 , k = 2 ; System.out.println( "Value of P( " + n + "," + k + ")" + " is " + permutationCoeff(n, k) ); } } // This code is contributed by Nikita Tiwari.
n_square
295.java
0.9
// Java program to solve Gold Mine problem import java.util.Arrays; class GFG { static final int MAX = 100 ; // Returns maximum amount of gold that // can be collected when journey started // from first column and moves allowed // are right, right-up and right-down static int getMaxGold( int gold[][], int m, int n) { // Create a table for storing // intermediate results and initialize // all cells to 0. The first row of // goldMineTable gives the maximum // gold that the miner can collect // when starts that row int goldTable[][] = new int [m][n]; for ( int [] rows:goldTable) Arrays.fill(rows, 0 ); for ( int col = n- 1 ; col >= 0 ; col--) { for ( int row = 0 ; row < m; row++) { // Gold collected on going to // the cell on the right(->) int right = (col == n- 1 ) ? 0 : goldTable[row][col+ 1 ]; // Gold collected on going to // the cell to right up (/) int right_up = (row == 0 || col == n- 1 ) ? 0 : goldTable[row- 1 ][col+ 1 ]; // Gold collected on going to // the cell to right down (\) int right_down = (row == m- 1 || col == n- 1 ) ? 0 : goldTable[row+ 1 ][col+ 1 ]; // Max gold collected from taking // either of the above 3 paths goldTable[row][col] = gold[row][col] + Math.max(right, Math.max(right_up, right_down)); ; } } // The max amount of gold collected will be // the max value in first column of all rows int res = goldTable[ 0 ][ 0 ]; for ( int i = 1 ; i < m; i++) res = Math.max(res, goldTable[i][ 0 ]); return res; } //driver code public static void main(String arg[]) { int gold[][]= { { 1 , 3 , 1 , 5 }, { 2 , 2 , 4 , 1 }, { 5 , 0 , 2 , 3 }, { 0 , 6 , 1 , 2 } }; int m = 4 , n = 4 ; System.out.print(getMaxGold(gold, m, n)); } } // This code is contributed by Anant Agarwal.
n_square
298.java
0.9
// Java program to Rearrange positive // and negative numbers in a array import java.io.*; class GFG { /* Function to print an array */ static void printArray( int A[], int size) { for ( int i = 0 ; i < size; i++) System.out.print(A[i] + " " ); System.out.println(); } // Merges two subarrays of arr[]. // First subarray is arr[l..m] // Second subarray is arr[m+1..r] static void merge( int arr[], int l, int m, int r) { int i, j, k; int n1 = m - l + 1 ; int n2 = r - m; /* create temp arrays */ int L[] = new int [n1]; int R[] = new int [n2]; /* Copy data to temp arrays L[] and R[] */ for (i = 0 ; i < n1; i++) L[i] = arr[l + i]; for (j = 0 ; j < n2; j++) R[j] = arr[m + 1 + j]; /* Merge the temp arrays back into arr[l..r]*/ // Initial index of first subarray i = 0 ; // Initial index of second subarray j = 0 ; // Initial index of merged subarray k = l; // Note the order of appearance of elements should // be maintained - we copy elements of left subarray // first followed by that of right subarray // copy negative elements of left subarray while (i < n1 && L[i] < 0 ) arr[k++] = L[i++]; // copy negative elements of right subarray while (j < n2 && R[j] < 0 ) arr[k++] = R[j++]; // copy positive elements of left subarray while (i < n1) arr[k++] = L[i++]; // copy positive elements of right subarray while (j < n2) arr[k++] = R[j++]; } // Function to Rearrange positive and negative // numbers in a array static void RearrangePosNeg( int arr[], int l, int r) { if (l < r) { // Same as (l + r)/2, but avoids overflow for // large l and h int m = l + (r - l) / 2 ; // Sort first and second halves RearrangePosNeg(arr, l, m); RearrangePosNeg(arr, m + 1 , r); merge(arr, l, m, r); } } // Driver program public static void main(String[] args) { int arr[] = { - 12 , 11 , - 13 , - 5 , 6 , - 7 , 5 , - 3 , - 6 }; int arr_size = arr.length; RearrangePosNeg(arr, 0 , arr_size - 1 ); printArray(arr, arr_size); } } // This code is contributed by vt_m.
n_square
30.java
0.9
// A Dynamic Programming solution for subset // sum problem class GFG { // Returns true if there is a subset of // set[] with sun equal to given sum static boolean isSubsetSum( int set[], int n, int sum) { // The value of subset[i][j] will be // true if there is a subset of // set[0..j-1] with sum equal to i boolean subset[][] = new boolean [sum+ 1 ][n+ 1 ]; // If sum is 0, then answer is true for ( int i = 0 ; i <= n; i++) subset[ 0 ][i] = true ; // If sum is not 0 and set is empty, // then answer is false for ( int i = 1 ; i <= sum; i++) subset[i][ 0 ] = false ; // Fill the subset table in botton // up manner for ( int i = 1 ; i <= sum; i++) { for ( int j = 1 ; j <= n; j++) { subset[i][j] = subset[i][j- 1 ]; if (i >= set[j- 1 ]) subset[i][j] = subset[i][j] || subset[i - set[j- 1 ]][j- 1 ]; } } /* // uncomment this code to print table for (int i = 0; i <= sum; i++) { for (int j = 0; j <= n; j++) System.out.println (subset[i][j]); } */ return subset[sum][n]; } /* Driver program to test above function */ public static void main (String args[]) { int set[] = { 3 , 34 , 4 , 12 , 5 , 2 }; int sum = 9 ; int n = set.length; if (isSubsetSum(set, n, sum) == true ) System.out.println( "Found a subset" + " with given sum" ); else System.out.println( "No subset with" + " given sum" ); } } /* This code is contributed by Rajat Mishra */
n_square
303.java
0.9
// Java program to check if there is a subset // with sum divisible by m. import java.util.Arrays; class GFG { // Returns true if there is a subset // of arr[] with sum divisible by m static boolean modularSum( int arr[], int n, int m) { if (n > m) return true ; // This array will keep track of all // the possible sum (after modulo m) // which can be made using subsets of arr[] // initialising boolean array with all false boolean DP[]= new boolean [m]; Arrays.fill(DP, false ); // we'll loop through all the elements // of arr[] for ( int i = 0 ; i < n; i++) { // anytime we encounter a sum divisible // by m, we are done if (DP[ 0 ]) return true ; // To store all the new encountered sum // (after modulo). It is used to make // sure that arr[i] is added only to // those entries for which DP[j] // was true before current iteration. boolean temp[] = new boolean [m]; Arrays.fill(temp, false ); // For each element of arr[], we loop // through all elements of DP table // from 1 to m and we add current // element i. e., arr[i] to all those // elements which are true in DP table for ( int j = 0 ; j < m; j++) { // if an element is true in // DP table if (DP[j] == true ) { if (DP[(j + arr[i]) % m] == false ) // We update it in temp and update // to DP once loop of j is over temp[(j + arr[i]) % m] = true ; } } // Updating all the elements of temp // to DP table since iteration over // j is over for ( int j = 0 ; j < m; j++) if (temp[j]) DP[j] = true ; // Also since arr[i] is a single // element subset, arr[i]%m is one // of the possible sum DP[arr[i] % m] = true ; } return DP[ 0 ]; } //driver code public static void main(String arg[]) { int arr[] = { 1 , 7 }; int n = arr.length; int m = 5 ; if (modularSum(arr, n, m)) System.out.print( "YES\n" ); else System.out.print( "NO\n" ); } } //This code is contributed by Anant Agarwal.
n_square
304.java
0.9
import java.util.Arrays; // Java program to find the largest // subset which where each pair // is divisible. class GFG { // function to find the longest Subsequence static int largestSubset( int [] a, int n) { // Sort array in increasing order Arrays.sort(a); // dp[i] is going to store size of largest // divisible subset beginning with a[i]. int [] dp = new int [n]; // Since last element is largest, d[n-1] is 1 dp[n - 1 ] = 1 ; // Fill values for smaller elements. for ( int i = n - 2 ; i >= 0 ; i--) { // Find all multiples of a[i] and consider // the multiple that has largest subset // beginning with it. int mxm = 0 ; for ( int j = i + 1 ; j < n; j++) { if (a[j] % a[i] == 0 ) { mxm = Math.max(mxm, dp[j]); } } dp[i] = 1 + mxm; } // Return maximum value from dp[] return Arrays.stream(dp).max().getAsInt(); } // driver code to check the above function public static void main(String[] args) { int [] a = { 1 , 3 , 6 , 13 , 17 , 18 }; int n = a.length; System.out.println(largestSubset(a, n)); } } /* This JAVA code is contributed by Rajput-Ji*/
n_square
305.java
0.9
// A Dynamic Programming solution for Rod cutting problem class RodCutting { /* Returns the best obtainable price for a rod of length n and price[] as prices of different pieces */ static int cutRod( int price[], int n) { int val[] = new int [n+ 1 ]; val[ 0 ] = 0 ; // Build the table val[] in bottom up manner and return // the last entry from the table for ( int i = 1 ; i<=n; i++) { int max_val = Integer.MIN_VALUE; for ( int j = 0 ; j < i; j++) max_val = Math.max(max_val, price[j] + val[i-j- 1 ]); val[i] = max_val; } return val[n]; } /* Driver program to test above functions */ public static void main(String args[]) { int arr[] = new int [] { 1 , 5 , 8 , 9 , 10 , 17 , 17 , 20 }; int size = arr.length; System.out.println( "Maximum Obtainable Value is " + cutRod(arr, size)); } } /* This code is contributed by Rajat Mishra */
n_square
307.java
0.9
// A memoization based Java program to // count even length binary sequences // such that the sum of first and // second half bits is same import java.io.*; class GFG { // A lookup table to store the results of // subproblems static int lookup[][] = new int [ 1000 ][ 1000 ]; // dif is diference between sums of first // n bits and last n bits i.e., // dif = (Sum of first n bits) - (Sum of last n bits) static int countSeqUtil( int n, int dif) { // We can't cover diference of // more than n with 2n bits if (Math.abs(dif) > n) return 0 ; // n == 1, i.e., 2 bit long sequences if (n == 1 && dif == 0 ) return 2 ; if (n == 1 && Math.abs(dif) == 1 ) return 1 ; // Check if this subbproblem is already // solved n is added to dif to make // sure index becomes positive if (lookup[n][n+dif] != - 1 ) return lookup[n][n+dif]; int res = // First bit is 0 & last bit is 1 countSeqUtil(n- 1 , dif+ 1 ) + // First and last bits are same 2 *countSeqUtil(n- 1 , dif) + // First bit is 1 & last bit is 0 countSeqUtil(n- 1 , dif- 1 ); // Store result in lookup table // and return the result return lookup[n][n+dif] = res; } // A Wrapper over countSeqUtil(). It mainly // initializes lookup table, then calls // countSeqUtil() static int countSeq( int n) { // Initialize all entries of lookup // table as not filled // memset(lookup, -1, sizeof(lookup)); for ( int k = 0 ; k < lookup.length; k++) { for ( int j = 0 ; j < lookup.length; j++) { lookup[k][j] = - 1 ; } } // call countSeqUtil() return countSeqUtil(n, 0 ); } // Driver program public static void main(String[] args) { int n = 2 ; System.out.println( "Count of sequences is " + countSeq( 2 )); } } // This code is contributed by Prerna Saini
n_square
311.java
0.9
// Efficient java program to count total number // of special sequences of length n where class Sequences { // DP based function to find the number of special // sequences static int getTotalNumberOfSequences( int m, int n) { // define T and build in bottom manner to store // number of special sequences of length n and // maximum value m int T[][]= new int [m+ 1 ][n+ 1 ]; for ( int i= 0 ; i<m+ 1 ; i++) { for ( int j= 0 ; j<n+ 1 ; j++) { // Base case : If length of sequence is 0 // or maximum value is 0, there cannot // exist any special sequence if (i == 0 || j == 0 ) T[i][j] = 0 ; // if length of sequence is more than // the maximum value, special sequence // cannot exist else if (i < j) T[i][j] = 0 ; // If length of sequence is 1 then the // number of special sequences is equal // to the maximum value // For example with maximum value 2 and // length 1, there can be 2 special // sequences {1}, {2} else if (j == 1 ) T[i][j] = i; // otherwise calculate else T[i][j] = T[i- 1 ][j] + T[i/ 2 ][j- 1 ]; } } return T[m][n]; } // main function public static void main (String[] args) { int m = 10 ; int n = 4 ; System.out.println( "Total number of possible sequences " + getTotalNumberOfSequences(m, n)); } }
n_square
314.java
0.9
// java program to find maximum // sum of bi-tonic sub-sequence import java.io.*; class GFG { // Function return maximum sum // of Bi-tonic sub-sequence static int MaxSumBS( int arr[], int n) { int max_sum = Integer.MIN_VALUE; // MSIBS[i] ==> Maximum sum Increasing Bi-tonic // subsequence ending with arr[i] // MSDBS[i] ==> Maximum sum Decreasing Bi-tonic // subsequence starting with arr[i] // Initialize MSDBS and MSIBS values as arr[i] for // all indexes int MSIBS[] = new int [n]; int MSDBS[] = new int [n]; for ( int i = 0 ; i < n; i++) { MSDBS[i] = arr[i]; MSIBS[i] = arr[i]; } // Compute MSIBS values from left to right */ for ( int i = 1 ; i < n; i++) for ( int j = 0 ; j < i; j++) if (arr[i] > arr[j] && MSIBS[i] < MSIBS[j] + arr[i]) MSIBS[i] = MSIBS[j] + arr[i]; // Compute MSDBS values from right to left for ( int i = n - 2 ; i >= 0 ; i--) for ( int j = n - 1 ; j > i; j--) if (arr[i] > arr[j] && MSDBS[i] < MSDBS[j] + arr[i]) MSDBS[i] = MSDBS[j] + arr[i]; // Find the maximum value of MSIBS[i] + // MSDBS[i] - arr[i] for ( int i = 0 ; i < n; i++) max_sum = Math.max(max_sum, (MSDBS[i] + MSIBS[i] - arr[i])); // return max sum of bi-tonic // sub-sequence return max_sum; } // Driver program public static void main(String[] args) { int arr[] = { 1 , 15 , 51 , 45 , 33 , 100 , 12 , 18 , 9 }; int n = arr.length; System.out.println( "Maximum Sum : " + MaxSumBS(arr, n)); } } // This code is contributed by vt_m
n_square
317.java
0.9
/* Dynamic Programming Java implementation of Maximum Sum Increasing Subsequence (MSIS) problem */ class GFG { /* maxSumIS() returns the maximum sum of increasing subsequence in arr[] of size n */ static int maxSumIS( int arr[], int n) { int i, j, max = 0 ; int msis[] = new int [n]; /* Initialize msis values for all indexes */ for (i = 0 ; i < n; i++) msis[i] = arr[i]; /* Compute maximum sum values in bottom up manner */ for (i = 1 ; i < n; i++) for (j = 0 ; j < i; j++) if (arr[i] > arr[j] && msis[i] < msis[j] + arr[i]) msis[i] = msis[j] + arr[i]; /* Pick maximum of all msis values */ for (i = 0 ; i < n; i++) if (max < msis[i]) max = msis[i]; return max; } // Driver code public static void main(String args[]) { int arr[] = new int []{ 1 , 101 , 2 , 3 , 100 , 4 , 5 }; int n = arr.length; System.out.println( "Sum of maximum sum " + "increasing subsequence is " + maxSumIS(arr, n)); } } // This code is contributed // by Rajat Mishra
n_square
318.java
0.9
/* Dynamic programming Java implementation of maximum product of an increasing subsequence */ import java.util.Arrays; import java.util.Collections; class GFG { // Returns product of maximum product // increasing subsequence. static int lis( int [] arr, int n) { int [] mpis = new int [n]; int max = Integer.MIN_VALUE; /* Initialize MPIS values */ for ( int i = 0 ; i < n; i++) mpis[i] = arr[i]; /* Compute optimized MPIS values considering every element as ending element of sequence */ for ( int i = 1 ; i < n; i++) for ( int j = 0 ; j < i; j++) if (arr[i] > arr[j] && mpis[i] < (mpis[j] * arr[i])) mpis[i] = mpis[j] * arr[i]; /* Pick maximum of all product values using for loop*/ for ( int k = 0 ; k < mpis.length; k++) { if (mpis[k] > max) { max = mpis[k]; } } return max; } // Driver program to test above function static public void main(String[] args) { int [] arr = { 3 , 100 , 4 , 5 , 150 , 6 }; int n = arr.length; System.out.println(lis(arr, n)); } } // This code is contributed by parashar.
n_square
319.java
0.9
// Java program to find the longest subsequence // such that the difference between adjacent // elements of the subsequence is one. import java.io.*; class GFG { // Function to find the length of longest // subsequence static int longestSubseqWithDiffOne( int arr[], int n) { // Initialize the dp[] array with 1 as a // single element will be of 1 length int dp[] = new int [n]; for ( int i = 0 ; i< n; i++) dp[i] = 1 ; // Start traversing the given array for ( int i = 1 ; i < n; i++) { // Compare with all the previous // elements for ( int j = 0 ; j < i; j++) { // If the element is consecutive // then consider this subsequence // and update dp[i] if required. if ((arr[i] == arr[j] + 1 ) || (arr[i] == arr[j] - 1 )) dp[i] = Math.max(dp[i], dp[j]+ 1 ); } } // Longest length will be the maximum // value of dp array. int result = 1 ; for ( int i = 0 ; i < n ; i++) if (result < dp[i]) result = dp[i]; return result; } // Driver code public static void main(String[] args) { // Longest subsequence with one // difference is // {1, 2, 3, 4, 3, 2} int arr[] = { 1 , 2 , 3 , 4 , 5 , 3 , 2 }; int n = arr.length; System.out.println(longestSubseqWithDiffOne( arr, n)); } } // This code is contributed by Prerna Saini
n_square
322.java
0.9
// JAVA Code for Maximum length subsequence // with difference between adjacent elements // as either 0 or 1 import java.util.*; class GFG { // function to find maximum length subsequence // with difference between adjacent elements as // either 0 or 1 public static int maxLenSub( int arr[], int n) { int mls[] = new int [n], max = 0 ; // Initialize mls[] values for all indexes for ( int i = 0 ; i < n; i++) mls[i] = 1 ; // Compute optimized maximum length // subsequence values in bottom up manner for ( int i = 1 ; i < n; i++) for ( int j = 0 ; j < i; j++) if (Math.abs(arr[i] - arr[j]) <= 1 && mls[i] < mls[j] + 1 ) mls[i] = mls[j] + 1 ; // Store maximum of all 'mls' values in 'max' for ( int i = 0 ; i < n; i++) if (max < mls[i]) max = mls[i]; // required maximum length subsequence return max; } /* Driver program to test above function */ public static void main(String[] args) { int arr[] = { 2 , 5 , 6 , 3 , 7 , 6 , 5 , 8 }; int n = arr.length; System.out.println( "Maximum length subsequence = " + maxLenSub(arr, n)); } } // This code is contributed by Arnav Kr. Mandal.
n_square
323.java
0.9
// Java program to find maximum sum increasing // subsequence tiint i-th index and including // k-th index. class GFG { static int pre_compute( int a[], int n, int index, int k) { int dp[][] = new int [n][n]; // Initializing the first row of // the dp[][]. for ( int i = 0 ; i < n; i++) { if (a[i] > a[ 0 ]) dp[ 0 ][i] = a[i] + a[ 0 ]; else dp[ 0 ][i] = a[i]; } // Creating the dp[][] matrix. for ( int i = 1 ; i < n; i++) { for ( int j = 0 ; j < n; j++) { if (a[j] > a[i] && j > i) { if (dp[i - 1 ][i] + a[j] > dp[i - 1 ][j]) dp[i][j] = dp[i - 1 ][i] + a[j]; else dp[i][j] = dp[i - 1 ][j]; } else dp[i][j] = dp[i - 1 ][j]; } } // To calculate for i=4 and k=6. return dp[index][k]; } // Driver code public static void main(String[] args) { int a[] = { 1 , 101 , 2 , 3 , 100 , 4 , 5 }; int n = a.length; int index = 4 , k = 6 ; System.out.println( pre_compute(a, n, index, k)); } } // This code is contributed by Smitha.
n_square
324.java
0.9
class Pair{ int a; int b; public Pair( int a, int b) { this .a = a; this .b = b; } // This function assumes that arr[] is sorted in increasing order // according the first (or smaller) values in pairs. static int maxChainLength(Pair arr[], int n) { int i, j, max = 0 ; int mcl[] = new int [n]; /* Initialize MCL (max chain length) values for all indexes */ for ( i = 0 ; i < n; i++ ) mcl[i] = 1 ; /* Compute optimized chain length values in bottom up manner */ for ( i = 1 ; i < n; i++ ) for ( j = 0 ; j < i; j++ ) if ( arr[i].a > arr[j].b && mcl[i] < mcl[j] + 1 ) mcl[i] = mcl[j] + 1 ; // mcl[i] now stores the maximum chain length ending with pair i /* Pick maximum of all MCL values */ for ( i = 0 ; i < n; i++ ) if ( max < mcl[i] ) max = mcl[i]; return max; } /* Driver program to test above function */ public static void main(String[] args) { Pair arr[] = new Pair[] { new Pair( 5 , 24 ), new Pair( 15 , 25 ), new Pair ( 27 , 40 ), new Pair( 50 , 60 )}; System.out.println( "Length of maximum size chain is " + maxChainLength(arr, arr.length)); } }
n_square
325.java
0.9
// JAVA Code for Maximum size square // sub-matrix with all 1s public class GFG { // method for Maximum size square sub-matrix with all 1s static void printMaxSubSquare( int M[][]) { int i,j; int R = M.length; //no of rows in M[][] int C = M[ 0 ].length; //no of columns in M[][] int S[][] = new int [R][C]; int max_of_s, max_i, max_j; /* Set first column of S[][]*/ for (i = 0 ; i < R; i++) S[i][ 0 ] = M[i][ 0 ]; /* Set first row of S[][]*/ for (j = 0 ; j < C; j++) S[ 0 ][j] = M[ 0 ][j]; /* Construct other entries of S[][]*/ for (i = 1 ; i < R; i++) { for (j = 1 ; j < C; j++) { if (M[i][j] == 1 ) S[i][j] = Math.min(S[i][j- 1 ], Math.min(S[i- 1 ][j], S[i- 1 ][j- 1 ])) + 1 ; else S[i][j] = 0 ; } } /* Find the maximum entry, and indexes of maximum entry in S[][] */ max_of_s = S[ 0 ][ 0 ]; max_i = 0 ; max_j = 0 ; for (i = 0 ; i < R; i++) { for (j = 0 ; j < C; j++) { if (max_of_s < S[i][j]) { max_of_s = S[i][j]; max_i = i; max_j = j; } } } System.out.println( "Maximum size sub-matrix is: " ); for (i = max_i; i > max_i - max_of_s; i--) { for (j = max_j; j > max_j - max_of_s; j--) { System.out.print(M[i][j] + " " ); } System.out.println(); } } // Driver program public static void main(String[] args) { int M[][] = {{ 0 , 1 , 1 , 0 , 1 }, { 1 , 1 , 0 , 1 , 0 }, { 0 , 1 , 1 , 1 , 0 }, { 1 , 1 , 1 , 1 , 0 }, { 1 , 1 , 1 , 1 , 1 }, { 0 , 0 , 0 , 0 , 0 }}; printMaxSubSquare(M); } }
n_square
328.java
0.9
// Java Code for Maximum weight path ending at // any element of last row in a matrix import java.util.*; class GFG { /* Function which return the maximum weight path sum */ public static int maxCost( int mat[][], int N) { // create 2D matrix to store the sum of // the path int dp[][]= new int [N][N]; dp[ 0 ][ 0 ] = mat[ 0 ][ 0 ]; // Initialize first column of total // weight array (dp[i to N][0]) for ( int i = 1 ; i < N; i++) dp[i][ 0 ] = mat[i][ 0 ] + dp[i- 1 ][ 0 ]; // Calculate rest path sum of weight matrix for ( int i = 1 ; i < N; i++) for ( int j = 1 ; j < i + 1 && j < N; j++) dp[i][j] = mat[i][j] + Math.max(dp[i- 1 ][j- 1 ], dp[i- 1 ][j]); // find the max weight path sum to reach // the last row int result = 0 ; for ( int i = 0 ; i < N; i++) if (result < dp[N- 1 ][i]) result = dp[N- 1 ][i]; // return maximum weight path sum return result; } /* Driver program to test above function */ public static void main(String[] args) { int mat[][] = { { 4 , 1 , 5 , 6 , 1 }, { 2 , 9 , 2 , 11 , 10 }, { 15 , 1 , 3 , 15 , 2 }, { 16 , 92 , 41 , 4 , 3 }, { 8 , 142 , 6 , 4 , 8 } }; int N = 5 ; System.out.println( "Maximum Path Sum : " + maxCost(mat, N)); } } // This code is contributed by Arnav Kr. Mandal.
n_square
332.java
0.9
// Java program to find Maximum path sum // start any column in row '0' and ends // up to any column in row 'n-1' import java.util.*; class GFG { static int N = 4 ; // function find maximum sum path static int MaximumPath( int Mat[][]) { int result = 0 ; // creat 2D matrix to store the sum // of the path int dp[][] = new int [N][N + 2 ]; // initialize all dp matrix as '0' for ( int [] rows : dp) Arrays.fill(rows, 0 ); // copy all element of first column into // 'dp' first column for ( int i = 0 ; i < N; i++) dp[ 0 ][i + 1 ] = Mat[ 0 ][i]; for ( int i = 1 ; i < N; i++) for ( int j = 1 ; j <= N; j++) dp[i][j] = Math.max(dp[i - 1 ][j - 1 ], Math.max(dp[i - 1 ][j], dp[i - 1 ][j + 1 ])) + Mat[i][j - 1 ]; // Find maximum path sum that end ups // at any column of last row 'N-1' for ( int i = 0 ; i <= N; i++) result = Math.max(result, dp[N - 1 ][i]); // return maximum sum path return result; } // driver code public static void main(String arg[]) { int Mat[][] = { { 4 , 2 , 3 , 4 }, { 2 , 9 , 1 , 10 }, { 15 , 1 , 3 , 0 }, { 16 , 92 , 41 , 44 } }; System.out.println(MaximumPath(Mat)); } } // This code is contributed by Anant Agarwal.
n_square
335.java
0.9
/* Java program for Dynamic Programming implementation of Min Cost Path problem */ import java.util.*; class MinimumCostPath { /* A utility function that returns minimum of 3 integers */ private static int min( int x, int y, int z) { if (x < y) return (x < z)? x : z; else return (y < z)? y : z; } private static int minCost( int cost[][], int m, int n) { int i, j; int tc[][]= new int [m+ 1 ][n+ 1 ]; tc[ 0 ][ 0 ] = cost[ 0 ][ 0 ]; /* Initialize first column of total cost(tc) array */ for (i = 1 ; i <= m; i++) tc[i][ 0 ] = tc[i- 1 ][ 0 ] + cost[i][ 0 ]; /* Initialize first row of tc array */ for (j = 1 ; j <= n; j++) tc[ 0 ][j] = tc[ 0 ][j- 1 ] + cost[ 0 ][j]; /* Construct rest of the tc array */ for (i = 1 ; i <= m; i++) for (j = 1 ; j <= n; j++) tc[i][j] = min(tc[i- 1 ][j- 1 ], tc[i- 1 ][j], tc[i][j- 1 ]) + cost[i][j]; return tc[m][n]; } /* Driver program to test above functions */ public static void main(String args[]) { int cost[][]= {{ 1 , 2 , 3 }, { 4 , 8 , 2 }, { 1 , 5 , 3 }}; System.out.println(minCost(cost, 2 , 2 )); } } // This code is contributed by Pankaj Kumar
n_square
337.java
0.9
// JAVA Code for Minimum number of jumps to reach end class GFG{ private static int minJumps( int [] arr, int n) { int jumps[] = new int [n]; // jumps[n-1] will hold the // result int i, j; if (n == 0 || arr[ 0 ] == 0 ) return Integer.MAX_VALUE; // if first element is 0, // end cannot be reached jumps[ 0 ] = 0 ; // Find the minimum number of jumps to reach arr[i] // from arr[0], and assign this value to jumps[i] for (i = 1 ; i < n; i++) { jumps[i] = Integer.MAX_VALUE; for (j = 0 ; j < i; j++) { if (i <= j + arr[j] && jumps[j] != Integer.MAX_VALUE) { jumps[i] = Math.min(jumps[i], jumps[j] + 1 ); break ; } } } return jumps[n- 1 ]; } // driver program to test above function public static void main(String[] args) { int arr[] = { 1 , 3 , 6 , 1 , 0 , 9 }; System.out.println( "Minimum number of jumps to reach end is : " + minJumps(arr,arr.length)); } } // This code is contributed by Arnav Kr. Mandal.
n_square
339.java
0.9
// Java program to find minimum removals // to make max-min <= K import java.util.Arrays; class GFG { static int MAX= 100 ; static int dp[][]= new int [MAX][MAX]; // function to check all possible combinations // of removal and return the minimum one static int countRemovals( int a[], int i, int j, int k) { // base case when all elements are removed if (i >= j) return 0 ; // if condition is satisfied, no more // removals are required else if ((a[j] - a[i]) <= k) return 0 ; // if the state has already been visited else if (dp[i][j] != - 1 ) return dp[i][j]; // when Amax-Amin>d else if ((a[j] - a[i]) > k) { // minimum is taken of the removal // of minimum element or removal // of the maximum element dp[i][j] = 1 + Math.min(countRemovals(a, i + 1 , j, k), countRemovals(a, i, j - 1 , k)); } return dp[i][j]; } // To sort the array and return the answer static int removals( int a[], int n, int k) { // sort the array Arrays.sort(a); // fill all stated with -1 // when only one element for ( int [] rows:dp) Arrays.fill(rows,- 1 ); if (n == 1 ) return 0 ; else return countRemovals(a, 0 , n - 1 , k); } // Driver code public static void main (String[] args) { int a[] = { 1 , 3 , 4 , 9 , 10 , 11 , 12 , 17 , 20 }; int n = a.length; int k = 4 ; System.out.print(removals(a, n, k)); } } // This code is contributed by Anant Agarwal.
n_square
342.java
0.9
// A Dynamic Programming based Java program to find minimum // number operations to convert str1 to str2 class EDIST { static int min( int x, int y, int z) { if (x <= y && x <= z) return x; if (y <= x && y <= z) return y; else return z; } static int editDistDP(String str1, String str2, int m, int n) { // Create a table to store results of subproblems int dp[][] = new int [m+ 1 ][n+ 1 ]; // Fill d[][] in bottom up manner for ( int i= 0 ; i<=m; i++) { for ( int j= 0 ; j<=n; j++) { // If first string is empty, only option is to // insert all characters of second string if (i== 0 ) dp[i][j] = j; // Min. operations = j // If second string is empty, only option is to // remove all characters of second string else if (j== 0 ) dp[i][j] = i; // Min. operations = i // If last characters are same, ignore last char // and recur for remaining string else if (str1.charAt(i- 1 ) == str2.charAt(j- 1 )) dp[i][j] = dp[i- 1 ][j- 1 ]; // If the last character is different, consider all // possibilities and find the minimum else dp[i][j] = 1 + min(dp[i][j- 1 ], // Insert dp[i- 1 ][j], // Remove dp[i- 1 ][j- 1 ]); // Replace } } return dp[m][n]; } public static void main(String args[]) { String str1 = "sunday" ; String str2 = "saturday" ; System.out.println( editDistDP( str1 , str2 , str1.length(), str2.length()) ); } } /*This code is contributed by Rajat Mishra*/
n_square
344.java
0.9
// Java implementation of finding length of longest // Common substring using Dynamic Programming public class LongestCommonSubSequence { /* Returns length of longest common substring of X[0..m-1] and Y[0..n-1] */ static int LCSubStr( char X[], char Y[], int m, int n) { // Create a table to store lengths of longest common suffixes of // substrings. Note that LCSuff[i][j] contains length of longest // common suffix of X[0..i-1] and Y[0..j-1]. The first row and // first column entries have no logical meaning, they are used only // for simplicity of program int LCStuff[][] = new int [m + 1 ][n + 1 ]; int result = 0 ; // To store length of the longest common substring // Following steps build LCSuff[m+1][n+1] in bottom up fashion for ( int i = 0 ; i <= m; i++) { for ( int j = 0 ; j <= n; j++) { if (i == 0 || j == 0 ) LCStuff[i][j] = 0 ; else if (X[i - 1 ] == Y[j - 1 ]) { LCStuff[i][j] = LCStuff[i - 1 ][j - 1 ] + 1 ; result = Integer.max(result, LCStuff[i][j]); } else LCStuff[i][j] = 0 ; } } return result; } // Driver Program to test above function public static void main(String[] args) { String X = "OldSite:GeeksforGeeks.org" ; String Y = "NewSite:GeeksQuiz.com" ; int m = X.length(); int n = Y.length(); System.out.println( "Length of Longest Common Substring is " + LCSubStr(X.toCharArray(), Y.toCharArray(), m, n)); } } // This code is contributed by Sumit Ghosh
n_square
346.java
0.9
// Space optimized CPP implementation of // longest common substring. import java.io.*; import java.util.*; public class GFG { // Function to find longest // common substring. static int LCSubStr(String X, String Y) { // Find length of both the strings. int m = X.length(); int n = Y.length(); // Variable to store length of longest // common substring. int result = 0 ; // Matrix to store result of two // consecutive rows at a time. int [][]len = new int [ 2 ][n]; // Variable to represent which row of // matrix is current row. int currRow = 0 ; // For a particular value of // i and j, len[currRow][j] // stores length of longest // common substring in string // X[0..i] and Y[0..j]. for ( int i = 0 ; i < m; i++) { for ( int j = 0 ; j < n; j++) { if (i == 0 || j == 0 ) { len[currRow][j] = 0 ; } else if (X.charAt(i - 1 ) == Y.charAt(j - 1 )) { len[currRow][j] = len[( 1 - currRow)][(j - 1 )] + 1 ; result = Math.max(result, len[currRow][j]); } else { len[currRow][j] = 0 ; } } // Make current row as previous // row and previous row as // new current row. currRow = 1 - currRow; } return result; } // Driver Code public static void main(String args[]) { String X = "GeeksforGeeks" ; String Y = "GeeksQuiz" ; System.out.print(LCSubStr(X, Y)); } } // This code is contributed by // Manish Shaw (manishshaw1)
n_square
348.java
0.9
// Program to find minimum // total offerings required import java.io.*; class GFG { // Returns minimum // offerings required static int offeringNumber( int n, int templeHeight[]) { int sum = 0 ; // Initialize result // Go through all // temples one by one for ( int i = 0 ; i < n; ++i) { // Go to left while // height keeps increasing int left = 0 , right = 0 ; for ( int j = i - 1 ; j >= 0 ; --j) { if (templeHeight[j] < templeHeight[j + 1 ]) ++left; else break ; } // Go to right while // height keeps increasing for ( int j = i + 1 ; j < n; ++j) { if (templeHeight[j] < templeHeight[j - 1 ]) ++right; else break ; } // This temple should offer // maximum of two values // to follow the rule. sum += Math.max(right, left) + 1 ; } return sum; } // Driver code public static void main (String[] args) { int arr1[] = { 1 , 2 , 2 }; System.out.println(offeringNumber( 3 , arr1)); int arr2[] = { 1 , 4 , 3 , 6 , 2 , 1 }; System.out.println(offeringNumber( 6 , arr2)); } } // This code is contributed by akt_mit
n_square
357.java
0.9
// Java program to print // equal sum sets of array. import java.io.*; import java.util.*; class GFG { // Function to print equal // sum sets of array. static void printEqualSumSets( int []arr, int n) { int i, currSum, sum = 0 ; // Finding sum of array elements for (i = 0 ; i < arr.length; i++) sum += arr[i]; // Check sum is even or odd. // If odd then array cannot // be partitioned. Print -1 // and return. if ((sum & 1 ) == 1 ) { System.out.print( "-1" ); return ; } // Divide sum by 2 to find // sum of two possible subsets. int k = sum >> 1 ; // Boolean DP table to store // result of states. // dp[i,j] = true if there is a // subset of elements in first i // elements of array that has sum // equal to j. boolean [][]dp = new boolean [n + 1 ][k + 1 ]; // If number of elements are zero, // then no sum can be obtained. for (i = 1 ; i <= k; i++) dp[ 0 ][i] = false ; // Sum 0 can be obtained by // not selecting any element. for (i = 0 ; i <= n; i++) dp[i][ 0 ] = true ; // Fill the DP table // in bottom up manner. for (i = 1 ; i <= n; i++) { for (currSum = 1 ; currSum <= k; currSum++) { // Excluding current element. dp[i][currSum] = dp[i - 1 ][currSum]; // Including current element if (arr[i - 1 ] <= currSum) dp[i][currSum] = dp[i][currSum] | dp[i - 1 ][currSum - arr[i - 1 ]]; } } // Required sets set1 and set2. List<Integer> set1 = new ArrayList<Integer>(); List<Integer> set2 = new ArrayList<Integer>(); // If partition is not possible // print -1 and return. if (!dp[n][k]) { System.out.print( "-1\n" ); return ; } // Start from last // element in dp table. i = n; currSum = k; while (i > 0 && currSum >= 0 ) { // If current element does // not contribute to k, then // it belongs to set 2. if (dp[i - 1 ][currSum]) { i--; set2.add(arr[i]); } // If current element contribute // to k then it belongs to set 1. else if (dp[i - 1 ][currSum - arr[i - 1 ]]) { i--; currSum -= arr[i]; set1.add(arr[i]); } } // Print elements of both the sets. System.out.print( "Set 1 elements: " ); for (i = 0 ; i < set1.size(); i++) System.out.print(set1.get(i) + " " ); System.out.print( "\nSet 2 elements: " ); for (i = 0 ; i < set2.size(); i++) System.out.print(set2.get(i) + " " ); } // Driver Code public static void main(String args[]) { int []arr = new int []{ 5 , 5 , 1 , 11 }; int n = arr.length; printEqualSumSets(arr, n); } } // This code is contributed by // Manish Shaw(manishshaw1)
n_square
363.java
0.9
/* Dynamic Programming implementation in Java for longest bitonic subsequence problem */ import java.util.*; import java.lang.*; import java.io.*; class LBS { /* lbs() returns the length of the Longest Bitonic Subsequence in arr[] of size n. The function mainly creates two temporary arrays lis[] and lds[] and returns the maximum lis[i] + lds[i] - 1. lis[i] ==> Longest Increasing subsequence ending with arr[i] lds[i] ==> Longest decreasing subsequence starting with arr[i] */ static int lbs( int arr[], int n ) { int i, j; /* Allocate memory for LIS[] and initialize LIS values as 1 for all indexes */ int [] lis = new int [n]; for (i = 0 ; i < n; i++) lis[i] = 1 ; /* Compute LIS values from left to right */ for (i = 1 ; i < n; i++) for (j = 0 ; j < i; j++) if (arr[i] > arr[j] && lis[i] < lis[j] + 1 ) lis[i] = lis[j] + 1 ; /* Allocate memory for lds and initialize LDS values for all indexes */ int [] lds = new int [n]; for (i = 0 ; i < n; i++) lds[i] = 1 ; /* Compute LDS values from right to left */ for (i = n- 2 ; i >= 0 ; i--) for (j = n- 1 ; j > i; j--) if (arr[i] > arr[j] && lds[i] < lds[j] + 1 ) lds[i] = lds[j] + 1 ; /* Return the maximum value of lis[i] + lds[i] - 1*/ int max = lis[ 0 ] + lds[ 0 ] - 1 ; for (i = 1 ; i < n; i++) if (lis[i] + lds[i] - 1 > max) max = lis[i] + lds[i] - 1 ; return max; } public static void main (String[] args) { int arr[] = { 0 , 8 , 4 , 12 , 2 , 10 , 6 , 14 , 1 , 9 , 5 , 13 , 3 , 11 , 7 , 15 }; int n = arr.length; System.out.println( "Length of LBS is " + lbs( arr, n )); } }
n_square
366.java
0.9
// A Space optimized Dynamic Programming // based Java program for LPS problem class GFG { // Returns the length of the longest // palindromic subsequence in str static int lps(String s) { int n = s.length(); // a[i] is going to store length // of longest palindromic subsequence // of substring s[0..i] int a[] = new int [n]; // Pick starting point for ( int i = n - 1 ; i >= 0 ; i--) { int back_up = 0 ; // Pick ending points and see if s[i] // increases length of longest common // subsequence ending with s[j]. for ( int j = i; j < n; j++) { // similar to 2D array L[i][j] == 1 // i.e., handling substrings of length // one. if (j == i) a[j] = 1 ; // Similar to 2D array L[i][j] = L[i+1][j-1]+2 // i.e., handling case when corner characters // are same. else if (s.charAt(i) == s.charAt(j)) { int temp = a[j]; a[j] = back_up + 2 ; back_up = temp; } // similar to 2D array L[i][j] = max(L[i][j-1], // a[i+1][j]) else { back_up = a[j]; a[j] = Math.max(a[j - 1 ], a[j]); } } } return a[n - 1 ]; } /* Driver program to test above functions */ public static void main(String[] args) { String str = "GEEKSFORGEEKS" ; System.out.println(lps(str)); } } //This article is contributed by prerna saini.
n_square
367.java
0.9
// Java code to Count Palindromic Subsequence // in a given String public class GFG { // Function return the total palindromic // subsequence static int countPS(String str) { int N = str.length(); // create a 2D array to store the count // of palindromic subsequence int [][] cps = new int [N+ 1 ][N+ 1 ]; // palindromic subsequence of length 1 for ( int i = 0 ; i < N; i++) cps[i][i] = 1 ; // check subsequence of length L is // palindrome or not for ( int L= 2 ; L<=N; L++) { for ( int i = 0 ; i < N; i++) { int k = L + i - 1 ; if (k < N){ if (str.charAt(i) == str.charAt(k)) cps[i][k] = cps[i][k- 1 ] + cps[i+ 1 ][k] + 1 ; else cps[i][k] = cps[i][k- 1 ] + cps[i+ 1 ][k] - cps[i+ 1 ][k- 1 ]; } } } // return total palindromic subsequence return cps[ 0 ][N- 1 ]; } // Driver program public static void main(String args[]) { String str = "abcb" ; System.out.println( "Total palindromic " + "subsequence are : " + countPS(str)); } } // This code is contributed by Sumit Ghosh
n_square
368.java
0.9
// Java Solution public class LongestPalinSubstring { // A utility function to print a substring str[low..high] static void printSubStr(String str, int low, int high) { System.out.println(str.substring(low, high + 1 )); } // This function prints the longest palindrome substring // of str[]. // It also returns the length of the longest palindrome static int longestPalSubstr(String str) { int n = str.length(); // get length of input string // table[i][j] will be false if substring str[i..j] // is not palindrome. // Else table[i][j] will be true boolean table[][] = new boolean [n][n]; // All substrings of length 1 are palindromes int maxLength = 1 ; for ( int i = 0 ; i < n; ++i) table[i][i] = true ; // check for sub-string of length 2. int start = 0 ; for ( int i = 0 ; i < n - 1 ; ++i) { if (str.charAt(i) == str.charAt(i + 1 )) { table[i][i + 1 ] = true ; start = i; maxLength = 2 ; } } // Check for lengths greater than 2. k is length // of substring for ( int k = 3 ; k <= n; ++k) { // Fix the starting index for ( int i = 0 ; i < n - k + 1 ; ++i) { // Get the ending index of substring from // starting index i and length k int j = i + k - 1 ; // checking for sub-string from ith index to // jth index iff str.charAt(i+1) to // str.charAt(j-1) is a palindrome if (table[i + 1 ][j - 1 ] && str.charAt(i) == str.charAt(j)) { table[i][j] = true ; if (k > maxLength) { start = i; maxLength = k; } } } } System.out.print( "Longest palindrome substring is; " ); printSubStr(str, start, start + maxLength - 1 ); return maxLength; // return length of LPS } // Driver program to test above functions public static void main(String[] args) { String str = "forgeeksskeegfor" ; System.out.println( "Length is: " + longestPalSubstr(str)); } } // This code is contributed by Sumit Ghosh
n_square
369.java
0.9
// Java program to find palindromic substrings of a string public class GFG { // Returns total number of palindrome substring of // length greater then equal to 2 static int CountPS( char str[], int n) { // create empty 2-D matrix that counts all palindrome // substring. dp[i][j] stores counts of palindromic // substrings in st[i..j] int dp[][] = new int [n][n]; // P[i][j] = true if substring str[i..j] is palindrome, // else false boolean P[][] = new boolean [n][n]; // palindrome of single length for ( int i= 0 ; i< n; i++) P[i][i] = true ; // palindrome of length 2 for ( int i= 0 ; i<n- 1 ; i++) { if (str[i] == str[i+ 1 ]) { P[i][i+ 1 ] = true ; dp[i][i+ 1 ] = 1 ; } } // Palindromes of length more than 2. This loop is similar // to Matrix Chain Multiplication. We start with a gap of // length 2 and fill the DP table in a way that gap between // starting and ending indexes increases one by one by // outer loop. for ( int gap= 2 ; gap<n; gap++) { // Pick starting point for current gap for ( int i= 0 ; i<n-gap; i++) { // Set ending point int j = gap + i; // If current string is palindrome if (str[i] == str[j] && P[i+ 1 ][j- 1 ] ) P[i][j] = true ; // Add current palindrome substring ( + 1) // and rest palindrome substring (dp[i][j-1] + dp[i+1][j]) // remove common palindrome substrings (- dp[i+1][j-1]) if (P[i][j] == true ) dp[i][j] = dp[i][j- 1 ] + dp[i+ 1 ][j] + 1 - dp[i+ 1 ][j- 1 ]; else dp[i][j] = dp[i][j- 1 ] + dp[i+ 1 ][j] - dp[i+ 1 ][j- 1 ]; } } // return total palindromic substrings return dp[ 0 ][n- 1 ]; } // Driver Method public static void main(String[] args) { String str = "abaab" ; System.out.println(CountPS(str.toCharArray(), str.length())); } }
n_square
370.java
0.9
// Java program to query number of palindromic // substrings of a string in a range import java.io.*; class GFG { // Function to construct the dp array static void constructDp( int dp[][], String str) { int l = str.length(); // declare 2D array isPalin, isPalin[i][j] will // be 1 if str(i..j) is palindrome int [][] isPalin = new int [l + 1 ][l + 1 ]; // initialize dp and isPalin array by zeros for ( int i = 0 ; i <= l; i++) { for ( int j = 0 ; j <= l; j++) { isPalin[i][j] = dp[i][j] = 0 ; } } // loop for starting index of range for ( int i = l - 1 ; i >= 0 ; i--) { // initialize value for one character strings as 1 isPalin[i][i] = 1 ; dp[i][i] = 1 ; // loop for ending index of range for ( int j = i + 1 ; j < l; j++) { /* isPalin[i][j] will be 1 if ith and jth characters are equal and mid substring str(i+1..j-1) is also a palindrome */ isPalin[i][j] = (str.charAt(i) == str.charAt(j) && (i + 1 > j - 1 || (isPalin[i + 1 ][j - 1 ]) != 0 )) ? 1 : 0 ; /* dp[i][j] will be addition of number of palindromes from i to j-1 and i+1 to j subtracting palindromes from i+1 to j-1 (as counted twice) plus 1 if str(i..j) is also a palindrome */ dp[i][j] = dp[i][j - 1 ] + dp[i + 1 ][j] - dp[i + 1 ][j - 1 ] + isPalin[i][j]; } } } // method returns count of palindromic substring in range (l, r) static int countOfPalindromeInRange( int dp[][], int l, int r) { return dp[l][r]; } // driver program public static void main(String args[]) { int MAX = 50 ; String str = "xyaabax" ; int [][] dp = new int [MAX][MAX]; constructDp(dp, str); int l = 3 ; int r = 5 ; System.out.println(countOfPalindromeInRange(dp, l, r)); } } // Contributed by Pramod Kumar
n_square
371.java
0.9
// Java program to find sum of maximum // sum alternating sequence starting with // first element. public class GFG { // Return sum of maximum sum alternating // sequence starting with arr[0] and is first // decreasing. static int maxAlternateSum( int arr[], int n) { if (n == 1 ) return arr[ 0 ]; // create two empty array that store result of // maximum sum of alternate sub-sequence // stores sum of decreasing and increasing // sub-sequence int dec[] = new int [n]; // store sum of increasing and decreasing sun-sequence int inc[] = new int [n]; // As per question, first element must be part // of solution. dec[ 0 ] = inc[ 0 ] = arr[ 0 ]; int flag = 0 ; // Traverse remaining elements of array for ( int i= 1 ; i<n; i++) { for ( int j= 0 ; j<i; j++) { // IF current sub-sequence is decreasing the // update dec[j] if needed. dec[i] by current // inc[j] + arr[i] if (arr[j] > arr[i]) { dec[i] = Math.max(dec[i], inc[j]+arr[i]); // Revert the flag , if first decreasing // is found flag = 1 ; } // If next element is greater but flag should be 1 // i.e. this element should be counted after the // first decreasing element gets counted else if (arr[j] < arr[i] && flag == 1 ) // If current sub-sequence is increasing // then update inc[i] inc[i] = Math.max(inc[i], dec[j]+arr[i]); } } // find maximum sum in b/w inc[] and dec[] int result = Integer.MIN_VALUE; for ( int i = 0 ; i < n; i++) { if (result < inc[i]) result = inc[i]; if (result < dec[i]) result = dec[i]; } // return maximum sum alternate sun-sequence return result; } // Driver Method public static void main(String[] args) { int arr[]= { 8 , 2 , 3 , 5 , 7 , 9 , 10 }; System.out.println( "Maximum sum = " + maxAlternateSum(arr , arr.length)); } }
n_square
372.java
0.9
// Java program to find longest // alternating subsequence in an array import java.io.*; class GFG { // Function to return longest // alternating subsequence length static int zzis( int arr[], int n) { /*las[i][0] = Length of the longest alternating subsequence ending at index i and last element is greater than its previous element las[i][1] = Length of the longest alternating subsequence ending at index i and last element is smaller than its previous element */ int las[][] = new int [n][ 2 ]; /* Initialize all values from 1 */ for ( int i = 0 ; i < n; i++) las[i][ 0 ] = las[i][ 1 ] = 1 ; int res = 1 ; // Initialize result /* Compute values in bottom up manner */ for ( int i = 1 ; i < n; i++) { // Consider all elements as // previous of arr[i] for ( int j = 0 ; j < i; j++) { // If arr[i] is greater, then // check with las[j][1] if (arr[j] < arr[i] && las[i][ 0 ] < las[j][ 1 ] + 1 ) las[i][ 0 ] = las[j][ 1 ] + 1 ; // If arr[i] is smaller, then // check with las[j][0] if ( arr[j] > arr[i] && las[i][ 1 ] < las[j][ 0 ] + 1 ) las[i][ 1 ] = las[j][ 0 ] + 1 ; } /* Pick maximum of both values at index i */ if (res < Math.max(las[i][ 0 ], las[i][ 1 ])) res = Math.max(las[i][ 0 ], las[i][ 1 ]); } return res; } /* Driver program */ public static void main(String[] args) { int arr[] = { 10 , 22 , 9 , 33 , 49 , 50 , 31 , 60 }; int n = arr.length; System.out.println( "Length of Longest " + "alternating subsequence is " + zzis(arr, n)); } } // This code is contributed by Prerna Saini
n_square
373.java
0.9
// Java program to print postorder // traversal from preorder and // inorder traversals import java.util.Arrays; class GFG { // A utility function to search x in arr[] of size n static int search( int arr[], int x, int n) { for ( int i = 0 ; i < n; i++) if (arr[i] == x) return i; return - 1 ; } // Prints postorder traversal from // given inorder and preorder traversals static void printPostOrder( int in1[], int pre[], int n) { // The first element in pre[] is // always root, search it in in[] // to find left and right subtrees int root = search(in1, pre[ 0 ], n); // If left subtree is not empty, // print left subtree if (root != 0 ) printPostOrder(in1, Arrays.copyOfRange(pre, 1 , n), root); // If right subtree is not empty, // print right subtree if (root != n - 1 ) printPostOrder(Arrays.copyOfRange(in1, root+ 1 , n), Arrays.copyOfRange(pre, 1 +root, n), n - root - 1 ); // Print root System.out.print( pre[ 0 ] + " " ); } // Driver code public static void main(String args[]) { int in1[] = { 4 , 2 , 5 , 1 , 3 , 6 }; int pre[] = { 1 , 2 , 4 , 5 , 3 , 6 }; int n = in1.length; System.out.println( "Postorder traversal " ); printPostOrder(in1, pre, n); } } // This code is contributed by Arnab Kundu
n_square
375.java
0.9
// Java program to print Postorder traversal from given Inorder // and Preorder traversals. public class PrintPost { static int preIndex = 0 ; void printPost( int [] in, int [] pre, int inStrt, int inEnd) { if (inStrt > inEnd) return ; // Find index of next item in preorder traversal in // inorder. int inIndex = search(in, inStrt, inEnd, pre[preIndex++]); // traverse left tree printPost(in, pre, inStrt, inIndex - 1 ); // traverse right tree printPost(in, pre, inIndex + 1 , inEnd); // print root node at the end of traversal System.out.print(in[inIndex] + " " ); } int search( int [] in, int startIn, int endIn, int data) { int i = 0 ; for (i = startIn; i < endIn; i++) if (in[i] == data) return i; return i; } // Driver code public static void main(String ars[]) { int in[] = { 4 , 2 , 5 , 1 , 3 , 6 }; int pre[] = { 1 , 2 , 4 , 5 , 3 , 6 }; int len = in.length; PrintPost tree = new PrintPost(); tree.printPost(in, pre, 0 , len - 1 ); } }
n_square
376.java
0.9
// Java program for recursive level order traversal in spiral form /* A binary tree node has data, pointer to left child and a pointer to right child */ class Node { int data; Node left, right; public Node( int d) { data = d; left = right = null ; } } class BinaryTree { Node root; // Function to print the spiral traversal of tree void printSpiral(Node node) { int h = height(node); int i; /* ltr -> left to right. If this variable is set then the given label is traversed from left to right */ boolean ltr = false ; for (i = 1 ; i <= h; i++) { printGivenLevel(node, i, ltr); /*Revert ltr to traverse next level in opposite order*/ ltr = !ltr; } } /* Compute the "height" of a tree -- the number of nodes along the longest path from the root node down to the farthest leaf node.*/ int height(Node node) { if (node == null ) return 0 ; else { /* compute the height of each subtree */ int lheight = height(node.left); int rheight = height(node.right); /* use the larger one */ if (lheight > rheight) return (lheight + 1 ); else return (rheight + 1 ); } } /* Print nodes at a given level */ void printGivenLevel(Node node, int level, boolean ltr) { if (node == null ) return ; if (level == 1 ) System.out.print(node.data + " " ); else if (level > 1 ) { if (ltr != false ) { printGivenLevel(node.left, level - 1 , ltr); printGivenLevel(node.right, level - 1 , ltr); } else { printGivenLevel(node.right, level - 1 , ltr); printGivenLevel(node.left, level - 1 , ltr); } } } /* Driver program to test the above functions */ 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( 7 ); tree.root.left.right = new Node( 6 ); tree.root.right.left = new Node( 5 ); tree.root.right.right = new Node( 4 ); System.out.println( "Spiral order traversal of Binary Tree is " ); tree.printSpiral(tree.root); } } // This code has been contributed by Mayank Jaiswal(mayank_24)
n_square
384.java
0.9
// A recursive java program to print reverse level order traversal // A binary tree node class Node { int data; Node left, right; Node( int item) { data = item; left = right; } } class BinaryTree { Node root; /* Function to print REVERSE level order traversal a tree*/ void reverseLevelOrder(Node node) { int h = height(node); int i; for (i = h; i >= 1 ; i--) //THE ONLY LINE DIFFERENT FROM NORMAL LEVEL ORDER { printGivenLevel(node, i); } } /* Print nodes at a given level */ void printGivenLevel(Node node, int level) { if (node == null ) return ; if (level == 1 ) System.out.print(node.data + " " ); else if (level > 1 ) { printGivenLevel(node.left, level - 1 ); printGivenLevel(node.right, level - 1 ); } } /* Compute the "height" of a tree -- the number of nodes along the longest path from the root node down to the farthest leaf node.*/ int height(Node node) { if (node == null ) return 0 ; else { /* compute the height of each subtree */ int lheight = height(node.left); int rheight = height(node.right); /* use the larger one */ if (lheight > rheight) return (lheight + 1 ); else return (rheight + 1 ); } } // Driver program to test above functions public static void main(String args[]) { BinaryTree tree = new BinaryTree(); // Let us create trees shown in above diagram 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 ); System.out.println( "Level Order traversal of binary tree is : " ); tree.reverseLevelOrder(tree.root); } } // This code has been contributed by Mayank Jaiswal
n_square
387.java
0.9
// Java program to construct a tree using inorder and preorder traversal /* A binary tree node has data, pointer to left child and a pointer to right child */ class Node { char data; Node left, right; Node( char item) { data = item; left = right = null ; } } class BinaryTree { Node root; static int preIndex = 0 ; /* Recursive function to construct binary of size len from Inorder traversal in[] and Preorder traversal pre[]. Initial values of inStrt and inEnd should be 0 and len -1. The function doesn't do any error checking for cases where inorder and preorder do not form a tree */ Node buildTree( char in[], char pre[], int inStrt, int inEnd) { if (inStrt > inEnd) return null ; /* Pick current node from Preorder traversal using preIndex and increment preIndex */ Node tNode = new Node(pre[preIndex++]); /* If this node has no children then return */ if (inStrt == inEnd) return tNode; /* Else find the index of this node in Inorder traversal */ int inIndex = search(in, inStrt, inEnd, tNode.data); /* Using index in Inorder traversal, construct left and right subtress */ tNode.left = buildTree(in, pre, inStrt, inIndex - 1 ); tNode.right = buildTree(in, pre, inIndex + 1 , inEnd); return tNode; } /* UTILITY FUNCTIONS */ /* Function to find index of value in arr[start...end] The function assumes that value is present in in[] */ int search( char arr[], int strt, int end, char value) { int i; for (i = strt; i <= end; i++) { if (arr[i] == value) return i; } return i; } /* This funtcion is here just to test buildTree() */ void printInorder(Node node) { if (node == null ) return ; /* first recur on left child */ printInorder(node.left); /* then print the data of node */ System.out.print(node.data + " " ); /* now recur on right child */ printInorder(node.right); } // driver program to test above functions public static void main(String args[]) { BinaryTree tree = new BinaryTree(); char in[] = new char [] { 'D' , 'B' , 'E' , 'A' , 'F' , 'C' }; char pre[] = new char [] { 'A' , 'B' , 'D' , 'E' , 'C' , 'F' }; int len = in.length; Node root = tree.buildTree(in, pre, 0 , len - 1 ); // building the tree by printing inorder traversal System.out.println( "Inorder traversal of constructed tree is : " ); tree.printInorder(root); } } // This code has been contributed by Mayank Jaiswal
n_square
396.java
0.9
// Java Program to construct ancestor matrix for a given tree import java.util.*; class GFG { // ancestorMatrix function to populate the matrix of public static void ancestorMatrix(Node root , int matrix[][], int size) { // base case: if (root== null ) return ; // call recursively for a preorder {left} ancestorMatrix(root.left, matrix, size); // call recursively for preorder {right} ancestorMatrix(root.right, matrix, size); // here we will reach the root node automatically // try solving on pen and paper if (root.left != null ) { // make the current node as parent of its children node matrix[root.data][root.left.data] = 1 ; // iterate through all the columns of children node // all nodes which are children to // children of root node will also // be children of root node for ( int i = 0 ; i < size; i++) { // if children of root node is a parent // of someone (i.e 1) then make that node // as children of root also if (matrix[root.left.data][i] == 1 ) matrix[root.data][i] = 1 ; } } // same procedure followed for right node as well if (root.right != null ) { matrix[root.data][root.right.data] = 1 ; for ( int i = 0 ; i < size; i++) { if (matrix[root.right.data][i]== 1 ) matrix[root.data][i] = 1 ; } } } // Driver program to test the program public static void main(String[] args) { // construct the binary tree as follows Node tree_root = new Node( 5 ); tree_root.left = new Node ( 1 ); tree_root.right = new Node( 2 ); tree_root.left.left = new Node( 0 ); tree_root.left.right = new Node( 4 ); tree_root.right.left = new Node( 3 ); // size of matrix int size = 6 ; int matrix [][] = new int [size][size]; ancestorMatrix(tree_root, matrix, size); for ( int i = 0 ; i < size; i++) { for ( int j = 0 ; j < size; j++) { System.out.print(matrix[i][j]+ " " ); } System.out.println(); } } // node class for tree node static class Node { public int data ; public Node left ,right; public Node ( int data) { this .data = data; this .left = this .right = null ; } } } // This code is contributed by Sparsh Singhal
n_square
401.java
0.9
// Java program to construct tree from inorder traversal /* A binary tree node has data, pointer to left child and a pointer to right child */ class Node { int data; Node left, right; Node( int item) { data = item; left = right = null ; } } class BinaryTree { Node root; /* Recursive function to construct binary of size len from Inorder traversal inorder[]. Initial values of start and end should be 0 and len -1. */ Node buildTree( int inorder[], int start, int end, Node node) { if (start > end) return null ; /* Find index of the maximum element from Binary Tree */ int i = max(inorder, start, end); /* Pick the maximum value and make it root */ node = new Node(inorder[i]); /* If this is the only element in inorder[start..end], then return it */ if (start == end) return node; /* Using index in Inorder traversal, construct left and right subtress */ node.left = buildTree(inorder, start, i - 1 , node.left); node.right = buildTree(inorder, i + 1 , end, node.right); return node; } /* UTILITY FUNCTIONS */ /* Function to find index of the maximum value in arr[start...end] */ int max( int arr[], int strt, int end) { int i, max = arr[strt], maxind = strt; for (i = strt + 1 ; i <= end; i++) { if (arr[i] > max) { max = arr[i]; maxind = i; } } return maxind; } /* This funtcion is here just to test buildTree() */ void printInorder(Node node) { if (node == null ) return ; /* first recur on left child */ printInorder(node.left); /* then print the data of node */ System.out.print(node.data + " " ); /* now recur on right child */ printInorder(node.right); } public static void main(String args[]) { BinaryTree tree = new BinaryTree(); /* Assume that inorder traversal of following tree is given 40 / \ 10 30 / \ 5 28 */ int inorder[] = new int []{ 5 , 10 , 40 , 30 , 28 }; int len = inorder.length; Node mynode = tree.buildTree(inorder, 0 , len - 1 , tree.root); /* Let us test the built tree by printing Inorder traversal */ System.out.println( "Inorder traversal of the constructed tree is " ); tree.printInorder(mynode); } } // This code has been contributed by Mayank Jaiswal
n_square
402.java
0.9
// Java program to construct a tree using inorder // and postorder traversals /* A binary tree node has data, pointer to left child and a pointer to right child */ class Node { int data; Node left, right; public Node( int data) { this .data = data; left = right = null ; } } // Class Index created to implement pass by reference of Index class Index { int index; } class BinaryTree { /* Recursive function to construct binary of size n from Inorder traversal in[] and Postrder traversal post[]. Initial values of inStrt and inEnd should be 0 and n -1. The function doesn't do any error checking for cases where inorder and postorder do not form a tree */ Node buildUtil( int in[], int post[], int inStrt, int inEnd, Index pIndex) { // Base case if (inStrt > inEnd) return null ; /* Pick current node from Postrder traversal using postIndex and decrement postIndex */ Node node = new Node(post[pIndex.index]); (pIndex.index)--; /* If this node has no children then return */ if (inStrt == inEnd) return node; /* Else find the index of this node in Inorder traversal */ int iIndex = search(in, inStrt, inEnd, node.data); /* Using index in Inorder traversal, construct left and right subtress */ node.right = buildUtil(in, post, iIndex + 1 , inEnd, pIndex); node.left = buildUtil(in, post, inStrt, iIndex - 1 , pIndex); return node; } // This function mainly initializes index of root // and calls buildUtil() Node buildTree( int in[], int post[], int n) { Index pIndex = new Index(); pIndex.index = n - 1 ; return buildUtil(in, post, 0 , n - 1 , pIndex); } /* Function to find index of value in arr[start...end] The function assumes that value is postsent in in[] */ int search( int arr[], int strt, int end, int value) { int i; for (i = strt; i <= end; i++) { if (arr[i] == value) break ; } return i; } /* This funtcion is here just to test */ void preOrder(Node node) { if (node == null ) return ; System.out.print(node.data + " " ); preOrder(node.left); preOrder(node.right); } public static void main(String[] args) { BinaryTree tree = new BinaryTree(); int in[] = new int [] { 4 , 8 , 2 , 5 , 1 , 6 , 3 , 7 }; int post[] = new int [] { 8 , 4 , 5 , 2 , 6 , 7 , 3 , 1 }; int n = in.length; Node root = tree.buildTree(in, post, n); System.out.println( "Preorder of the constructed tree : " ); tree.preOrder(root); } } // This code has been contributed by Mayank Jaiswal(mayank_24)
n_square
403.java
0.9
// Java program to convert an arbitrary binary tree to a tree that holds // children sum property // A binary tree node class Node { int data; Node left, right; Node( int item) { data = item; left = right = null ; } } class BinaryTree { Node root; /* This function changes a tree to hold children sum property */ void convertTree(Node node) { int left_data = 0 , right_data = 0 , diff; /* If tree is empty or it's a leaf node then return true */ if (node == null || (node.left == null && node.right == null )) return ; else { /* convert left and right subtrees */ convertTree(node.left); convertTree(node.right); /* If left child is not present then 0 is used as data of left child */ if (node.left != null ) left_data = node.left.data; /* If right child is not present then 0 is used as data of right child */ if (node.right != null ) right_data = node.right.data; /* get the diff of node's data and children sum */ diff = left_data + right_data - node.data; /* If node's children sum is greater than the node's data */ if (diff > 0 ) node.data = node.data + diff; /* THIS IS TRICKY --> If node's data is greater than children sum, then increment subtree by diff */ if (diff < 0 ) // -diff is used to make diff positive increment(node, -diff); } } /* This function is used to increment subtree by diff */ void increment(Node node, int diff) { /* IF left child is not NULL then increment it */ if (node.left != null ) { node.left.data = node.left.data + diff; // Recursively call to fix the descendants of node->left increment(node.left, diff); } else if (node.right != null ) // Else increment right child { node.right.data = node.right.data + diff; // Recursively call to fix the descendants of node->right increment(node.right, diff); } } /* Given a binary tree, printInorder() prints out its inorder traversal*/ void printInorder(Node node) { if (node == null ) return ; /* first recur on left child */ printInorder(node.left); /* then print the data of node */ System.out.print(node.data + " " ); /* now recur on right child */ printInorder(node.right); } // Driver program to test above functions public static void main(String args[]) { BinaryTree tree = new BinaryTree(); tree.root = new Node( 50 ); tree.root.left = new Node( 7 ); tree.root.right = new Node( 2 ); tree.root.left.left = new Node( 3 ); tree.root.left.right = new Node( 5 ); tree.root.right.left = new Node( 1 ); tree.root.right.right = new Node( 30 ); System.out.println( "Inorder traversal before conversion is :" ); tree.printInorder(tree.root); tree.convertTree(tree.root); System.out.println( "" ); System.out.println( "Inorder traversal after conversion is :" ); tree.printInorder(tree.root); } } // This code has been contributed by Mayank Jaiswal(mayank_24)
n_square
407.java
0.9
// Java program to check if Binary tree is sum tree or not /* A binary tree node has data, left child and right child */ class Node { int data; Node left, right, nextRight; Node( int item) { data = item; left = right = nextRight = null ; } } class BinaryTree { Node root; /* A utility function to get the sum of values in tree with root as root */ int sum(Node node) { if (node == null ) return 0 ; return sum(node.left) + node.data + sum(node.right); } /* returns 1 if sum property holds for the given node and both of its children */ int isSumTree(Node node) { int ls, rs; /* If node is NULL or it's a leaf node then return true */ if ((node == null ) || (node.left == null && node.right == null )) return 1 ; /* Get sum of nodes in left and right subtrees */ ls = sum(node.left); rs = sum(node.right); /* if the node and both of its children satisfy the property return 1 else 0*/ if ((node.data == ls + rs) && (isSumTree(node.left) != 0 ) && (isSumTree(node.right)) != 0 ) return 1 ; return 0 ; } /* Driver program to test above functions */ public static void main(String args[]) { BinaryTree tree = new BinaryTree(); tree.root = new Node( 26 ); tree.root.left = new Node( 10 ); tree.root.right = new Node( 3 ); tree.root.left.left = new Node( 4 ); tree.root.left.right = new Node( 6 ); tree.root.right.right = new Node( 3 ); if (tree.isSumTree(tree.root) != 0 ) System.out.println( "The given tree is a sum tree" ); else System.out.println( "The given tree is not a sum tree" ); } } // This code has been contributed by Mayank Jaiswal
n_square
416.java
0.9
// Java program to check if there exist an edge whose // removal creates two trees of same size class Node { int key; Node left, right; public Node( int key) { this .key = key; left = right = null ; } } class BinaryTree { Node root; // To calculate size of tree with given root int count(Node node) { if (node == null ) return 0 ; return count(node.left) + count(node.right) + 1 ; } // This function returns true if there is an edge // whose removal can divide the tree in two halves // n is size of tree boolean checkRec(Node node, int n) { // Base cases if (node == null ) return false ; // Check for root if (count(node) == n - count(node)) return true ; // Check for rest of the nodes return checkRec(node.left, n) || checkRec(node.right, n); } // This function mainly uses checkRec() boolean check(Node node) { // Count total nodes in given tree int n = count(node); // Now recursively check all nodes return checkRec(node, n); } // Driver code public static void main(String[] args) { BinaryTree tree = new BinaryTree(); tree.root = new Node( 5 ); tree.root.left = new Node( 1 ); tree.root.right = new Node( 6 ); tree.root.left.left = new Node( 3 ); tree.root.right.left = new Node( 7 ); tree.root.right.right = new Node( 4 ); if (tree.check(tree.root)== true ) System.out.println( "YES" ); else System.out.println( "NO" ); } } // This code has been contributed by Mayank Jaiswal(mayank_24)
n_square
421.java
0.9
/* Java program to check if all three given traversals are of the same tree */ import java.util.*; class GfG { static int preIndex = 0 ; // A Binary Tree Node static class Node { int data; Node left, right; } // Utility function to create a new tree node static Node newNode( int data) { Node temp = new Node(); temp.data = data; temp.left = null ; temp.right = null ; return temp; } /* Function to find index of value in arr[start...end] The function assumes that value is present in in[] */ static int search( int arr[], int strt, int end, int value) { for ( int i = strt; i <= end; i++) { if (arr[i] == value) return i; } return - 1 ; } /* Recursive function to construct binary tree of size len from Inorder traversal in[] and Preorder traversal pre[]. Initial values of inStrt and inEnd should be 0 and len -1. The function doesn't do any error checking for cases where inorder and preorder do not form a tree */ static Node buildTree( int in[], int pre[], int inStrt, int inEnd) { if (inStrt > inEnd) return null ; /* Pick current node from Preorder traversal using preIndex and increment preIndex */ Node tNode = newNode(pre[preIndex++]); /* If this node has no children then return */ if (inStrt == inEnd) return tNode; /* Else find the index of this node in Inorder traversal */ int inIndex = search(in, inStrt, inEnd, tNode.data); /* Using index in Inorder traversal, construct left and right subtress */ tNode.left = buildTree(in, pre, inStrt, inIndex- 1 ); tNode.right = buildTree(in, pre, inIndex+ 1 , inEnd); return tNode; } /* function to compare Postorder traversal on constructed tree and given Postorder */ static int checkPostorder(Node node, int postOrder[], int index) { if (node == null ) return index; /* first recur on left child */ index = checkPostorder(node.left,postOrder,index); /* now recur on right child */ index = checkPostorder(node.right,postOrder,index); /* Compare if data at current index in both Postorder traversals are same */ if (node.data == postOrder[index]) index++; else return - 1 ; return index; } // Driver program to test above functions public static void main(String[] args) { int inOrder[] = { 4 , 2 , 5 , 1 , 3 }; int preOrder[] = { 1 , 2 , 4 , 5 , 3 }; int postOrder[] = { 4 , 5 , 2 , 3 , 1 }; int len = inOrder.length; // build tree from given // Inorder and Preorder traversals Node root = buildTree(inOrder, preOrder, 0 , len - 1 ); // compare postorder traversal on constructed // tree with given Postorder traversal int index = checkPostorder(root,postOrder, 0 ); // If both postorder traversals are same if (index == len) System.out.println( "Yes" ); else System.out.println( "No" ); } }
n_square
423.java
0.9
// A Java program for Prim's Minimum Spanning Tree (MST) algorithm. // The program is for adjacency matrix representation of the graph import java.util.*; import java.lang.*; import java.io.*; class MST { // Number of vertices in the graph private static final int V = 5 ; // A utility function to find the vertex with minimum key // value, from the set of vertices not yet included in MST int minKey( int key[], Boolean mstSet[]) { // Initialize min value int min = Integer.MAX_VALUE, min_index = - 1 ; for ( int v = 0 ; v < V; v++) if (mstSet[v] == false && key[v] < min) { min = key[v]; min_index = v; } return min_index; } // A utility function to print the constructed MST stored in // parent[] void printMST( int parent[], int graph[][]) { System.out.println( "Edge \tWeight" ); for ( int i = 1 ; i < V; i++) System.out.println(parent[i] + " - " + i + "\t" + graph[i][parent[i]]); } // Function to construct and print MST for a graph represented // using adjacency matrix representation void primMST( int graph[][]) { // Array to store constructed MST int parent[] = new int [V]; // Key values used to pick minimum weight edge in cut int key[] = new int [V]; // To represent set of vertices not yet included in MST Boolean mstSet[] = new Boolean[V]; // Initialize all keys as INFINITE for ( int i = 0 ; i < V; i++) { key[i] = Integer.MAX_VALUE; mstSet[i] = false ; } // Always include first 1st vertex in MST. key[ 0 ] = 0 ; // Make key 0 so that this vertex is // picked as first vertex parent[ 0 ] = - 1 ; // First node is always root of MST // The MST will have V vertices for ( int count = 0 ; count < V - 1 ; count++) { // Pick thd minimum key vertex from the set of vertices // not yet included in MST int u = minKey(key, mstSet); // Add the picked vertex to the MST Set mstSet[u] = true ; // Update key value and parent index of the adjacent // vertices of the picked vertex. Consider only those // vertices which are not yet included in MST for ( int v = 0 ; v < V; v++) // graph[u][v] is non zero only for adjacent vertices of m // mstSet[v] is false for vertices not yet included in MST // Update the key only if graph[u][v] is smaller than key[v] if (graph[u][v] != 0 && mstSet[v] == false && graph[u][v] < key[v]) { parent[v] = u; key[v] = graph[u][v]; } } // print the constructed MST printMST(parent, graph); } public static void main(String[] args) { /* Let us create the following graph 2 3 (0)--(1)--(2) | / \ | 6| 8/ \5 |7 | / \ | (3)-------(4) 9 */ MST t = new MST(); int graph[][] = new int [][] { { 0 , 2 , 0 , 6 , 0 }, { 2 , 0 , 3 , 8 , 5 }, { 0 , 3 , 0 , 0 , 7 }, { 6 , 8 , 0 , 0 , 9 }, { 0 , 5 , 7 , 9 , 0 } }; // Print the solution t.primMST(graph); } } // This code is contributed by Aakash Hasija
n_square
465.java
0.9
// A Java program for Dijkstra's single source shortest path algorithm. // The program is for adjacency matrix representation of the graph import java.util.*; import java.lang.*; import java.io.*; class ShortestPath { // A utility function to find the vertex with minimum distance value, // from the set of vertices not yet included in shortest path tree static final int V= 9 ; int minDistance( int dist[], Boolean sptSet[]) { // Initialize min value int min = Integer.MAX_VALUE, min_index=- 1 ; for ( int v = 0 ; v < V; v++) if (sptSet[v] == false && dist[v] <= min) { min = dist[v]; min_index = v; } return min_index; } // A utility function to print the constructed distance array void printSolution( int dist[], int n) { System.out.println( "Vertex Distance from Source" ); for ( int i = 0 ; i < V; i++) System.out.println(i+ " tt " +dist[i]); } // Funtion that implements Dijkstra's single source shortest path // algorithm for a graph represented using adjacency matrix // representation void dijkstra( int graph[][], int src) { int dist[] = new int [V]; // The output array. dist[i] will hold // the shortest distance from src to i // sptSet[i] will true if vertex i is included in shortest // path tree or shortest distance from src to i is finalized Boolean sptSet[] = new Boolean[V]; // Initialize all distances as INFINITE and stpSet[] as false for ( int i = 0 ; i < V; i++) { dist[i] = Integer.MAX_VALUE; sptSet[i] = false ; } // Distance of source vertex from itself is always 0 dist[src] = 0 ; // Find shortest path for all vertices for ( int count = 0 ; count < V- 1 ; count++) { // Pick the minimum distance vertex from the set of vertices // not yet processed. u is always equal to src in first // iteration. int u = minDistance(dist, sptSet); // Mark the picked vertex as processed sptSet[u] = true ; // Update dist value of the adjacent vertices of the // picked vertex. for ( int v = 0 ; v < V; v++) // Update dist[v] only if is not in sptSet, there is an // edge from u to v, and total weight of path from src to // v through u is smaller than current value of dist[v] if (!sptSet[v] && graph[u][v]!= 0 && dist[u] != Integer.MAX_VALUE && dist[u]+graph[u][v] < dist[v]) dist[v] = dist[u] + graph[u][v]; } // print the constructed distance array printSolution(dist, V); } // Driver method public static void main (String[] args) { /* Let us create the example graph discussed above */ int graph[][] = new int [][]{{ 0 , 4 , 0 , 0 , 0 , 0 , 0 , 8 , 0 }, { 4 , 0 , 8 , 0 , 0 , 0 , 0 , 11 , 0 }, { 0 , 8 , 0 , 7 , 0 , 4 , 0 , 0 , 2 }, { 0 , 0 , 7 , 0 , 9 , 14 , 0 , 0 , 0 }, { 0 , 0 , 0 , 9 , 0 , 10 , 0 , 0 , 0 }, { 0 , 0 , 4 , 14 , 10 , 0 , 2 , 0 , 0 }, { 0 , 0 , 0 , 0 , 0 , 2 , 0 , 1 , 6 }, { 8 , 11 , 0 , 0 , 0 , 0 , 1 , 0 , 7 }, { 0 , 0 , 2 , 0 , 0 , 0 , 6 , 7 , 0 } }; ShortestPath t = new ShortestPath(); t.dijkstra(graph, 0 ); } } //This code is contributed by Aakash Hasija
n_square
467.java
0.9
// Java program to to maximize array // sum after k operations. class GFG { // This function does k operations // on array in a way that maximize // the array sum. index --> stores // the index of current minimum // element for j'th operation static int maximumSum( int arr[], int n, int k) { // Modify array K number of times for ( int i = 1 ; i <= k; i++) { int min = + 2147483647 ; int index = - 1 ; // Find minimum element in array for // current operation and modify it // i.e; arr[j] --> -arr[j] for ( int j= 0 ; j<n; j++) { if (arr[j] < min) { min = arr[j]; index = j; } } // this the condition if we find 0 as // minimum element, so it will useless to // replace 0 by -(0) for remaining operations if (min == 0 ) break ; // Modify element of array arr[index] = -arr[index]; } // Calculate sum of array int sum = 0 ; for ( int i = 0 ; i < n; i++) sum += arr[i]; return sum; } // Driver program public static void main(String arg[]) { int arr[] = {- 2 , 0 , 5 , - 1 , 2 }; int k = 4 ; int n = arr.length; System.out.print(maximumSum(arr, n, k)); } } // This code is contributed by Anant Agarwal.
n_square
471.java
0.9
// Java program to find lexicographically minimum // value after k swaps. class GFG { // Modifies arr[0..n-1] to lexicographically // smallest with k swaps. static void minimizeWithKSwaps( int arr[], int n, int k) { for ( int i = 0 ; i < n- 1 && k > 0 ; ++i) { // Set the position where we want // to put the smallest integer int pos = i; for ( int j = i+ 1 ; j < n ; ++j) { // If we exceed the Max swaps // then terminate the loop if (j - i > k) break ; // Find the minimum value from i+1 to // max k or n if (arr[j] < arr[pos]) pos = j; } // Swap the elements from Minimum position // we found till now to the i index int temp; for ( int j = pos; j>i; --j) { temp=arr[j]; arr[j]=arr[j- 1 ]; arr[j- 1 ]=temp; } // Set the final value after swapping pos-i // elements k -= pos-i; } } // Driver method public static void main(String[] args) { int arr[] = { 7 , 6 , 9 , 2 , 1 }; int n = arr.length; int k = 3 ; minimizeWithKSwaps(arr, n, k); //Print the final Array for ( int i= 0 ; i<n; ++i) System.out.print(arr[i] + " " ); } } // This code is contributed by Anant Agarwal.
n_square
488.java
0.9
// Java program to find // lexicographically // maximum value after // k swaps. import java.io.*; class GFG { static void SwapInts( int array[], int position1, int position2) { // Swaps elements // in an array. // Copy the first // position's element int temp = array[position1]; // Assign to the // second element array[position1] = array[position2]; // Assign to the // first element array[position2] = temp; } // Function which // modifies the array static void KSwapMaximum( int []arr, int n, int k) { for ( int i = 0 ; i < n - 1 && k > 0 ; ++i) { // Here, indexPositionition // is set where we want to // put the current largest // integer int indexPosition = i; for ( int j = i + 1 ; j < n; ++j) { // If we exceed the // Max swaps then // break the loop if (k <= j - i) break ; // Find the maximum value // from i+1 to max k or n // which will replace // arr[indexPosition] if (arr[j] > arr[indexPosition]) indexPosition = j; } // Swap the elements from // Maximum indexPosition // we found till now to // the ith index for ( int j = indexPosition; j > i; --j) SwapInts(arr, j, j - 1 ); // Updates k after swapping // indexPosition-i elements k -= indexPosition - i; } } // Driver code public static void main(String args[]) { int []arr = { 3 , 5 , 4 , 1 , 2 }; int n = arr.length; int k = 3 ; KSwapMaximum(arr, n, k); // Print the final Array for ( int i = 0 ; i < n; ++i) System.out.print(arr[i] + " " ); } } // This code is contributed by // Manish Shaw(manishshaw1)
n_square
489.java
0.9
// A Java program to implement greedy algorithm for graph coloring import java.io.*; import java.util.*; import java.util.LinkedList; // This class represents an undirected graph using adjacency list class Graph { private int V; // No. of vertices private LinkedList<Integer> adj[]; //Adjacency List //Constructor Graph( int v) { V = v; adj = new LinkedList[v]; for ( int i= 0 ; i<v; ++i) adj[i] = new LinkedList(); } //Function to add an edge into the graph void addEdge( int v, int w) { adj[v].add(w); adj[w].add(v); //Graph is undirected } // Assigns colors (starting from 0) to all vertices and // prints the assignment of colors void greedyColoring() { int result[] = new int [V]; // Initialize all vertices as unassigned Arrays.fill(result, - 1 ); // Assign the first color to first vertex result[ 0 ] = 0 ; // A temporary array to store the available colors. False // value of available[cr] would mean that the color cr is // assigned to one of its adjacent vertices boolean available[] = new boolean [V]; // Initially, all colors are available Arrays.fill(available, true ); // Assign colors to remaining V-1 vertices for ( int u = 1 ; u < V; u++) { // Process all adjacent vertices and flag their colors // as unavailable Iterator<Integer> it = adj[u].iterator() ; while (it.hasNext()) { int i = it.next(); if (result[i] != - 1 ) available[result[i]] = false ; } // Find the first available color int cr; for (cr = 0 ; cr < V; cr++){ if (available[cr]) break ; } result[u] = cr; // Assign the found color // Reset the values back to true for the next iteration Arrays.fill(available, true ); } // print the result for ( int u = 0 ; u < V; u++) System.out.println( "Vertex " + u + " ---> Color " + result[u]); } // Driver method public static void main(String args[]) { Graph g1 = new Graph( 5 ); g1.addEdge( 0 , 1 ); g1.addEdge( 0 , 2 ); g1.addEdge( 1 , 2 ); g1.addEdge( 1 , 3 ); g1.addEdge( 2 , 3 ); g1.addEdge( 3 , 4 ); System.out.println( "Coloring of graph 1" ); g1.greedyColoring(); System.out.println(); Graph g2 = new Graph( 5 ); g2.addEdge( 0 , 1 ); g2.addEdge( 0 , 2 ); g2.addEdge( 1 , 2 ); g2.addEdge( 1 , 4 ); g2.addEdge( 2 , 4 ); g2.addEdge( 4 , 3 ); System.out.println( "Coloring of graph 2 " ); g2.greedyColoring(); } } // This code is contributed by Aakash Hasija
n_square
490.java
0.9
// Java program to fin maximum cash // flow among a set of persons class GFG { // Number of persons (or vertices in the graph) static final int N = 3 ; // A utility function that returns // index of minimum value in arr[] static int getMin( int arr[]) { int minInd = 0 ; for ( int i = 1 ; i < N; i++) if (arr[i] < arr[minInd]) minInd = i; return minInd; } // A utility function that returns // index of maximum value in arr[] static int getMax( int arr[]) { int maxInd = 0 ; for ( int i = 1 ; i < N; i++) if (arr[i] > arr[maxInd]) maxInd = i; return maxInd; } // A utility function to return minimum of 2 values static int minOf2( int x, int y) { return (x < y) ? x: y; } // amount[p] indicates the net amount // to be credited/debited to/from person 'p' // If amount[p] is positive, then // i'th person will amount[i] // If amount[p] is negative, then // i'th person will give -amount[i] static void minCashFlowRec( int amount[]) { // Find the indexes of minimum and // maximum values in amount[] // amount[mxCredit] indicates the maximum amount // to be given (or credited) to any person . // And amount[mxDebit] indicates the maximum amount // to be taken(or debited) from any person. // So if there is a positive value in amount[], // then there must be a negative value int mxCredit = getMax(amount), mxDebit = getMin(amount); // If both amounts are 0, then // all amounts are settled if (amount[mxCredit] == 0 && amount[mxDebit] == 0 ) return ; // Find the minimum of two amounts int min = minOf2(-amount[mxDebit], amount[mxCredit]); amount[mxCredit] -= min; amount[mxDebit] += min; // If minimum is the maximum amount to be System.out.println( "Person " + mxDebit + " pays " + min + " to " + "Person " + mxCredit); // Recur for the amount array. // Note that it is guaranteed that // the recursion would terminate // as either amount[mxCredit] or // amount[mxDebit] becomes 0 minCashFlowRec(amount); } // Given a set of persons as graph[] // where graph[i][j] indicates // the amount that person i needs to // pay person j, this function // finds and prints the minimum // cash flow to settle all debts. static void minCashFlow( int graph[][]) { // Create an array amount[], // initialize all value in it as 0. int amount[]= new int [N]; // Calculate the net amount to // be paid to person 'p', and // stores it in amount[p]. The // value of amount[p] can be // calculated by subtracting // debts of 'p' from credits of 'p' for ( int p = 0 ; p < N; p++) for ( int i = 0 ; i < N; i++) amount[p] += (graph[i][p] - graph[p][i]); minCashFlowRec(amount); } // Driver code public static void main (String[] args) { // graph[i][j] indicates the amount // that person i needs to pay person j int graph[][] = { { 0 , 1000 , 2000 }, { 0 , 0 , 5000 }, { 0 , 0 , 0 },}; // Print the solution minCashFlow(graph); } } // This code is contributed by Anant Agarwal.
n_square
497.java
0.9
import java.util.*; import java.lang.*; class Main { static void minAbsSumPair( int arr[], int arr_size) { int inv_count = 0 ; int l, r, min_sum, sum, min_l, min_r; /* Array should have at least two elements*/ if (arr_size < 2 ) { System.out.println( "Invalid Input" ); return ; } /* Initialization of values */ min_l = 0 ; min_r = 1 ; min_sum = arr[ 0 ] + arr[ 1 ]; for (l = 0 ; l < arr_size - 1 ; l++) { for (r = l+ 1 ; r < arr_size; r++) { sum = arr[l] + arr[r]; if (Math.abs(min_sum) > Math.abs(sum)) { min_sum = sum; min_l = l; min_r = r; } } } System.out.println( " The two elements whose " + "sum is minimum are " + arr[min_l]+ " and " +arr[min_r]); } // main function public static void main (String[] args) { int arr[] = { 1 , 60 , - 10 , 70 , - 80 , 85 }; minAbsSumPair(arr, 6 ); } }
n_square
522.java
0.9
// Java implementation of simple // algorithm to find smaller // element on left side import java.io.*; class GFG { // Prints smaller elements on // left side of every element static void printPrevSmaller( int []arr, int n) { // Always print empty or '_' // for first element System.out.print( "_, " ); // Start from second element for ( int i = 1 ; i < n; i++) { // look for smaller // element on left of 'i' int j; for (j = i - 1 ; j >= 0 ; j--) { if (arr[j] < arr[i]) { System.out.print(arr[j] + ", " ); break ; } } // If there is no smaller // element on left of 'i' if (j == - 1 ) System.out.print( "_, " ) ; } } // Driver Code public static void main (String[] args) { int []arr = { 1 , 3 , 0 , 2 , 5 }; int n = arr.length; printPrevSmaller(arr, n); } } // This code is contributed by anuj_67.
n_square
550.java
0.9
import java.util.Scanner; public class Main { public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc=new Scanner(System.in); int n=sc.nextInt(); int[] arr = new int [n]; int maxindex=0; int minindex=0; int max; int min; for(int i=0;i<arr.length;i++) { arr[i]=sc.nextInt(); } int k=Integer.MAX_VALUE; for(int i=0;i<arr.length;i++) { for(int j=i;j<arr.length;j++) { if(i!=j) { int k1=Math.min(arr[i], arr[j])/Math.abs(i-j); if(k1<k) { k = k1; } } } } System.out.println(k); } }
n_square
556.java
0.9
import java.io.*; import java.util.*; public class hi { public static void main(String[] args) throws IOException{ Reader in=new Reader(); PrintWriter w = new PrintWriter(System.out); int n=in.nextInt(); int[] arr=in.nextIntArray(n); int k=Integer.MAX_VALUE; for (int i = 0; i < n; i++) { for (int j = i+1; j < n; j++) { int a=(int)Math.floor((Math.min(arr[i],arr[j])/Math.abs(i-j))); if(a < k) k=a; } } w.println(k); w.close(); return; } } class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String nextLine() throws IOException{ int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } public String next() throws IOException{ int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public int[] nextIntArray(int n) throws IOException{ int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } }
n_square
560.java
0.9
import java.util.*; import java.io.*; public class PartySweet { static BufferedReader br; static StringTokenizer tokenizer; public static void main(String[] args) throws Exception { br = new BufferedReader(new InputStreamReader(System.in)); int n = nextInt(), m = nextInt(); int[] b = new int[n]; int[] g = new int[m]; for(int i = 0; i < n; i++) b[i] = nextInt(); for(int i = 0; i < m; i++) g[i] = nextInt(); int total = 0; int max = 0, max2 = 0; for(int i = 0; i < n; i++) { if(b[i] > b[max]) { max2 = max; max = i; } else if(b[max2] < b[i]) max2 = i; } total += b[max] - b[max2]; for(int i = 0; i < n; i++) { for(int j = 0; j < m; j++) { if(b[i] > g[j]) { System.out.println(-1); return; } if(i != max) total += b[i]; else total += g[j]; } } System.out.println(total); } public static String next() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) { String line = br.readLine(); if (line == null) throw new IOException(); tokenizer = new StringTokenizer(line); } return tokenizer.nextToken(); } public static int nextInt() throws IOException { return Integer.parseInt(next()); } public static long nextLong() throws IOException { return Long.parseLong(next()); } public static double nextDouble() throws IOException { return Double.parseDouble(next()); } }
n_square
565.java
0.9
import java.io.*; import java.util.*; import static java.lang.System.*; public class Main{ public static void main(String[] args) throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(in)); StringTokenizer st = new StringTokenizer(br.readLine().trim()); int n = Integer.valueOf(st.nextToken()); int k = Integer.valueOf(st.nextToken()); String str = br.readLine().trim(); int [] arr = new int[n]; LL[] adjlist = new LL[n]; for(int i =0 ; i < n; i++){ int x = str.charAt(i) - 'a' + 1; arr[i] = x; adjlist[i] = new LL(); } Arrays.sort(arr); for(int i =0; i < n; i++){ for(int j = i + 1; j < n; j++){ int a = arr[i]; int b = arr[j]; if((b - a) >= 2){ adjlist[i].add(new Pair(j, arr[j], 1)); } } } LinkedList<Pair> list = new LinkedList<Pair>(); LinkedList<Pair> tmpList = new LinkedList<Pair>(); int ans = Integer.MAX_VALUE; for(int i = 0; i < n; i++){ list.clear(); list.add(new Pair(i,arr[i],0)); // out.println("---- "+arr[i]); for(int j = 0; j < k; j++){ tmpList.clear(); while(!list.isEmpty()){ Pair cur = list.removeFirst(); if(j == k-1){ ans = Math.min(cur.val, ans); } for(Pair adj : adjlist[cur.idx]){ tmpList.add(new Pair(adj.idx, adj.val + cur.val, cur.val+1)); } } // out.println(list.toString()); if(tmpList.size() == 0){ break; } else{ list.addAll(tmpList); } // out.println(list.toString()); } } if(ans == Integer.MAX_VALUE) out.println(-1); else out.println(ans); } public static class LL extends LinkedList<Pair>{} public static class Pair implements Comparable<Pair>{ int val; int idx; int ctr; public Pair(int a, int b, int c){ idx = a; val = b; ctr = c; } public int compareTo(Pair p){ if(ctr == p.ctr){ if(val == p.val) return idx - p.idx; return val - p.val; } return p.ctr - ctr; } public String toString(){ return val+", "; } } }
n_square
576.java
0.9
import java.util.Scanner; public class Codeforces { public static Scanner input = new Scanner(System.in); public static void main(String[] args){ int n,k; n=input.nextInt(); k=input.nextInt(); String s=input.next(); int[] wtArray=new int[n]; for(int i=0;i<s.length();i++) wtArray[i]=s.charAt(i)-96; for(int i=1;i<n;i++) for(int j=0;j<n-i;j++) if(wtArray[j]>wtArray[j+1]){ int temp=wtArray[j+1]; wtArray[j+1]=wtArray[j]; wtArray[j]=temp; } int sum=wtArray[0]; k--; int temp=sum; for(int i=1;k!=0 &&i <n;i++){ if((wtArray[i]-temp)>1){ sum+=wtArray[i]; k--; temp=wtArray[i]; } } if(k!=0) sum=-1; System.out.println(sum); } }
n_square
581.java
0.9
//Atcoder import java.io.*; import java.util.*; public class Main { static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner() { try { br = new BufferedReader(new InputStreamReader(System.in)); st = new StringTokenizer(br.readLine()); } catch (Exception e){e.printStackTrace();} } public String next() { if (st.hasMoreTokens()) return st.nextToken(); try {st = new StringTokenizer(br.readLine());} catch (Exception e) {e.printStackTrace();} return st.nextToken(); } public int nextInt() {return Integer.parseInt(next());} public long nextLong() {return Long.parseLong(next());} public double nextDouble() {return Double.parseDouble(next());} public String nextLine() { String line = ""; if(st.hasMoreTokens()) line = st.nextToken(); else try {return br.readLine();}catch(IOException e){e.printStackTrace();} while(st.hasMoreTokens()) line += " "+st.nextToken(); return line; } } public static void main(String[] args) { FastScanner sc = new FastScanner(); PrintWriter pw = new PrintWriter(System.out); int n = sc.nextInt(); int m = sc.nextInt(); int ans = 0; int[] a = new int[101]; for(int i=0;i<m;i++) a[sc.nextInt()]++; for(int i=1;i<=100;i++) { int y = 0; for(int x : a) { y += x / i; } if(y >= n) { ans = i; } } pw.println(ans); pw.close(); } }
n_square
583.java
0.9
// // _oo8oo_ // o8888888o // 88" . "88 // (| -_- |) // 0\ = /0 // ___/'==='\___ // .' \\| |// '. // / \\||| : |||// \ // / _||||| -:- |||||_ \ // | | \\\ - /// | | // | \_| ''\---/'' |_/ | // \ .-\__ '-' __/-. / // ___'. .' /--.--\ '. .'___ // ."" '< '.___\_<|>_/___.' >' "". // | | : `- \`.:`\ _ /`:.`/ -` : | | // \ \ `-. \_ __\ /__ _/ .-` / / // =====`-.____`.___ \_____/ ___.`____.-`===== // `=---=` // // // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // // 佛祖保佑 永不宕机/永无bug // import java.util.*; public class G { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n, m; n = in.nextInt(); m = in.nextInt(); int[] a = new int[m]; for (int i = 0; i < m; i++) { a[i] = in.nextInt(); } Arrays.sort(a); HashMap<Integer, Integer> map = new HashMap<>(200); for (int i : a) { Integer t = map.get(i); if (t == null) { map.put(i, 1); } else { map.put(i, t + 1); } } ArrayList<Food> list = new ArrayList<>(100); Iterator<Map.Entry<Integer, Integer>> it = map.entrySet().iterator(); while (it.hasNext()) { Map.Entry<Integer, Integer> en = it.next(); list.add(new Food(en.getKey(), en.getValue())); } list.sort(Comparator.comparingInt(o -> o.num)); int min, max; min = 1; max = list.get(list.size() - 1).num; int res = 0; for (int i = min; i <= max; i++) { int t = 0; for (Food food : list) { int gaven = food.num / i; if (gaven >= 1) { t += gaven; if (t >= n) { res = Math.max(res, i); break; } } } } System.out.println(res); // System.out.println(Arrays.toString(list.toArray())); // if (list.size() < n) { // System.out.println(0); // } else { // System.out.println(list.get(n - 1).num); // } } } class Food { int id; int num; public Food(int id, int num) { this.id = id; this.num = num; } @Override public String toString() { return "Food{" + "id=" + id + ", num=" + num + '}'; } }
n_square
585.java
0.9
import java.io.*; import java.util.*; public class Solution{ static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } public static void main(String args[] ) { FastReader sc = new FastReader(); int n = sc.nextInt(); int m = sc.nextInt(); int[] arr = new int[105]; for(int i=0;i<m;i++){ int a = sc.nextInt(); arr[a]++; } for(int i=1;i<=1000;i++){ int sum=0; for(int a:arr){ if(a!=0){ sum+=(a/i); } } if(sum<n){ System.out.println(i-1); return; } } } }
n_square
587.java
0.9
import java.util.Arrays; import java.util.Scanner; public class Solution { public static void main(String[] args) { Scanner sc = new Scanner(System.in); Solution ss = new Solution(); ss.test(sc); } void test(Scanner sc){ int LEN = sc.nextInt(); int[] a = new int[LEN]; int[] b = new int[LEN]; for (int i = 0; i < b.length; i++) { a[i] = sc.nextInt(); } for (int i = 0; i < b.length; i++) { b[i] = sc.nextInt(); } Arrays.sort(a); Arrays.sort(b); int ia=0, ib=0; while(ia<LEN && a[ia]==0) ia++; while(ib<LEN && b[ib]==0) ib++; if(ib==LEN){ System.out.println("Yes"); return; } if(ia==LEN){ System.out.println("No"); return; } boolean out = true; while(ia<LEN && ib<LEN){ if(a[ia]==b[ib]){ ia++; ib++; }else{ if(a[ia]>b[ib]){ while(ib<LEN && b[ib]!=a[ia]){ ib++; } if(ib==LEN){ out=false; break; } } } } if(out){ System.out.println("Yes"); }else{ System.out.println("No"); } } }
n_square
592.java
0.9
import java.util.*; import java.lang.*; import java.io.*; public class TestClass { // function for finding size of set public static int set_size(int[] a, int N){ HashSet <Integer> newset = new HashSet <Integer>(); int i=0; while(i<N){ newset.add(a[i++]); } int v = newset.size(); return v; } public static void main(String args[] ) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer tk = new StringTokenizer(br.readLine()); int N = Integer.parseInt(tk.nextToken()); int x = Integer.parseInt(tk.nextToken()); int[] a = new int[N]; int[] b = new int[N]; StringTokenizer tb = new StringTokenizer(br.readLine()); for(int i=0; i<N; i++){ a[i] = Integer.parseInt(tb.nextToken()); } if(set_size(a, N) < N){ System.out.print("0"); System.exit(0); } int num=0; while(num++<4){ for(int i=0; i<N; i++){ if((a[i]&x) == a[i]) continue; else{ for(int j=0; j<N; j++){ if(i==j){ b[i] = (a[i]&x); } else{ b[j] = a[j]; } } int s = set_size(b, N); if(s<N){ System.out.print(num); System.exit(0); } } } for(int i=0; i<N; i++) a[i] = b[i]; } System.out.print("-1"); System.exit(0); } }
n_square
595.java
0.9
import java.util.ArrayList; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class Cr500 { public static void main(String args[]) { Scanner scanner = new Scanner(System.in); int n, x, status = -1; Set<Integer> a = new HashSet<>(), bitA = new HashSet<>(); ArrayList<Integer> al = new ArrayList<>(), bl = new ArrayList<>(); n = scanner.nextInt(); x = scanner.nextInt(); for(int i = 0; i < n; i++) { int v; if(!a.add(v = scanner.nextInt())) { System.out.println(0); return; } if(!bitA.add(v & x)) { status = 2; } al.add(v); bl.add(v & x); } if(contains(al, bl)) { System.out.println(1); return; } System.out.println(status); } private static boolean contains(ArrayList<Integer> a, ArrayList<Integer> b) { for(int i = 0; i < a.size(); i++) { int v1 = a.get(i); for(int j = 0; j < b.size(); j++) { int v2 = b.get(j); if(i != j && v1 == v2) { return true; } } } return false; } }
n_square
596.java
0.9
import java.util.*; public class B { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); int x = scanner.nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = scanner.nextInt(); } Arrays.sort(a); List<Integer> list = new ArrayList<>(); for (int i = 0; i < n; i++) { list.add(a[i]); } for (int i = 0; i < n - 1; i++) { if (a[i] == a[i + 1]) { System.out.println(0); return; } } for (int i = n - 1; i > 0; i--) { if ((a[i] & x) == (a[i - 1] & x) && !list.contains(x)) { System.out.println(2); return; } else if (list.contains(x) && a[i] > x && (a[i] & x) == x) { System.out.println(1); return; } } System.out.println(-1); } }
n_square
598.java
0.9
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int m = in.nextInt(); int[] v = new int[n]; int[] ans = new int[n]; long s = 0; int t; for(int i=0; i<n;i++) { v[i] = in.nextInt(); s+=v[i]; } for(int i=0; i<n-1;i++) { for (int j = i + 1; j < n; j++) { if (v[j] > v[i]) { t = v[i]; v[i] = v[j]; v[j] = t; } } } for(int i=0; i<n-1; i++){ if(v[i] > v[i+1]){ ans[i] = v[i]-v[i+1]; } if(v[i] == v[i+1] && v[i]!=1){ ans[i]=1; v[i+1]--; } if(v[i] < v[i+1]){ ans[i]=1; v[i+1] = v[i]-1; if(v[i+1] == 0){ v[i+1] = 1; } } if(v[i] == 0 || v[i] == 1){ ans[i] = 1; v[i] = 1; } } if (v[n-1] > 1){ ans[n-1] = v[n-1]; } else{ ans[n-1] = 1; } for (int i=0; i<n; i++){ s-=ans[i]; } System.out.print(s); } }
n_square
608.java
0.9