Professional Documents
Culture Documents
1. Abbas has been assigned the task to find the minimum number of prime
numbers which when added will be equal to a given number N.
The function should return the minimum number of prime numbers which when
summed will result in input1.
If it is not possible to generate input1 by adding prime numbers, the function
should return -1
import java.util.*;
public class PrimeSum {
if (isValidIndex(i, 11))
{
arr[i] = Math.min(arr[i], 1 + arr[i - 11]);
}
if (isValidIndex(i, 17))
{
arr[i] = Math.min(arr[i], 1 + arr[i - 17]);
}
if (isValidIndex(i, 43))
{
arr[i] = Math.min(arr[i], 1 + arr[i - 43]);
}
if (isValidIndex(i, 93))
{
arr[i] = Math.min(arr[i], 1 + arr[i - 93]);
}
}
return arr[n] == 1000000000 ? -1 : arr[n];
}
public static void main(String args[])
{
Scanner s = new Scanner(System.in);
int n;
System.out.print("Enter the number: ");
n=s.nextInt();
int result = getMinPrimes(n);
if (result != -1)
{
System.out.print("Minimum required primes: ");
System.out.print(getMinPrimes(n));
}
else
{
System.out.print("-1");
}
}
}
1. Given an array of integers and an integer k, you need to find the total number of
continuous subarrays whose sum equals to k.
class Solution {
public int subarraySum(int[] nums, int k) {
HashMap<Integer,Integer> map = new HashMap<>();
int count = 0;
int sum = 0;
map.put(0,1);
for(int i =0; i < nums.length; i++){
sum += nums[i];
if(map.containsKey(sum - k)){
count += map.get(sum - k);
}
map.put(sum, map.getOrDefault(sum, 0) + 1);
}
return count;
}
}
Java Currency Formatter
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
NumberFormat us = NumberFormat.getCurrencyInstance(Locale.US);
NumberFormat india = NumberFormat.getCurrencyInstance(indiaLocale);
NumberFormat china = NumberFormat.getCurrencyInstance(Locale.CHINA);
NumberFormat france = NumberFormat.getCurrencyInstance(Locale.FRANCE);
/* Print output */
System.out.println("US: " + us.format(payment));
System.out.println("India: " + india.format(payment));
System.out.println("China: " + china.format(payment));
System.out.println("France: " + france.format(payment));
}
}
public static String getSmallestAndLargest(String s, int k) {
String smallest = "";
String largest = "";
String[] list = new String[s.length() - k + 1];
for (int i = 0; i <= s.length() - k; i++) {
String str = s.substring(i, i+k);
list[i] = str;
}
smallest = list[0];
largest = list[0];
for(int i = 1; i < list.length; i++) {
if (list[i].compareTo(smallest) < 0) {
smallest = list[i];
}
if (list[i].compareTo(largest) > 0){
largest = list[i];
}
}
return smallest + "\n" + largest;
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String s = scan.next();
int k = scan.nextInt();
scan.close();
System.out.println(getSmallestAndLargest(s, k));
}
}