Find maximum difference between two elements such that larger element appears after the smaller number in Java

Given array of integers, find Maximum difference between two elements such that larger element appears after the smaller number. public static int calculateMaxDifferenceBetweenTwoElements(int[] arr) { int minElementTillNow=arr[0]; int maxDifference=Integer.MIN_VALUE; for (int i = 0; i < arr.length; i++) { int difference=0; if(arr[i] >minElementTillNow) { difference=arr[i]-minElementTillNow; if(difference > maxDifference) { maxDifference=difference; } } else { minElementTillNow=arr[i]; … Read more

Stock Buy Sell to Maximize Profit in Java

Given an array of integers representing stock price on a single day, find max profit that can be earned by 1 transaction.So you need to find a pair (buyDay,sellDay) where buyDay < = sellDay and it should maximize the profit. For example: SOLUTION public static int calculateMaxProfit(int[] arr) { int lowestPriceTillThatDay = arr[0]; int maxProfit = Integer.MIN_VALUE; … Read more

Java Program to check if a vowel is present in the string?

We can use regular expression to check if the string contains vowels or not. public class StringContainsVowels { public static void main(String[] args) { System.out.println(stringContainsVowels(“Hello”)); // true System.out.println(stringContainsVowels(“TV”)); // false } public static boolean stringContainsVowels(String input) { return input.toLowerCase().matches(“.*[aeiou].*”); } }

How to reverse a String in Java?

It might be surprising, but there is no reverse() utility method in the String class. But, it’s a very simple task. We can create a character array from the string and then iterate it from the end to start. We can append the characters to a string builder and finally return the reversed string. public … Read more