# Java

## Find the Contiguous Subarray with Sum to a Given Value in an array in Java

Given an array of positive integer and given value X, find Contiguous sub array whose sum is equal to X.For example : static void findSubArraySumEqualToX(int arr[], int X) { int currentSum; for (int i = 0; i < arr.length; i++) { currentSum = arr[i]; // try all subarrays starting with ‘i’ for (int j = … Read more

## 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 swap two numbers without using a third variable?

int a = 10;int b = 20; b = b + a; // now b is sum of both the numbersa = b – a; // b – a = (b + a) – a = b (a is swapped)b = b – a; // (b + a) – b = a (b is swapped) … Read more

## 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