Posts

Showing posts from May, 2022

Java code to Split a String into Maximum number of Balanced Strings

Image
  We are given a string which contains only characters 'R' and 'L'. A balanced string is one which has equal number of 'R' and 'L' characters. The problem statement is to find the maximum number of balanced strings which can be extracted from an input String. Here is a link to the leetcode problem, and we'll try to solve it today. /**   * Split the String into maximum number of Balanced Strings   *   * @author computengine.com   * @param s   * @return  */ public int balancedStringSplit(String s) { int countR = 0 , countL = 0 , count = 0 ; // loop through the input string for ( int i = 0 ; i < s . length ( ) ; i + + ) { // increment if 'R' found if ( s . charAt ( i ) = = 'R' ) countR + + ; // increment if 'L' found if ( s . charAt ( i ) = = 'L' ) countL + + ; // increment counter when Number of 'R' match Number of 'L', and reset

Java code to find Count of Pairs in Integer Array with Absolute Difference K

Image
Let's solve a LeetCode problem using Java.  Count Number of Pairs With Absolute Difference K You can go through the problem and try to understand what needs to be done. Try to write your own code first. We have solved the problem and its here for your reference. /**  * Count Number of Pairs With Absolute Difference K  * @author computengine.com  * @param nums  * @param k  * @return  */ public int countKDifference ( int [ ] nums , int k ) { int count = 0 ; for ( int i = 0 ; i < nums . length ; i + + ) { for ( int j = i + 1 ; j < nums . length ; j + + ) { if ( Math . abs ( nums [ i ] - nums [ j ] ) = = k ) { count + + ; } } } return count ; } If you look closely, we have looped through the Integer Array, and compared two elements of the arrays and find the difference between them. Now the difference can be positive or negative but it has to be equal to the input K. So we've used Math.abs() function