0% found this document useful (0 votes)
6 views24 pages

Java Week

The document contains multiple Java code snippets for various programming problems, including palindrome checking, finding single numbers, calculating maximum profit from stock prices, and converting numbers to words. Each code snippet is structured with a main method that takes user input and processes it using a defined solution class. The solutions utilize standard Java libraries and data structures such as arrays, lists, and maps.

Uploaded by

kfakeid9
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views24 pages

Java Week

The document contains multiple Java code snippets for various programming problems, including palindrome checking, finding single numbers, calculating maximum profit from stock prices, and converting numbers to words. Each code snippet is structured with a main method that takes user input and processes it using a defined solution class. The solutions utilize standard Java libraries and data structures such as arrays, lists, and maps.

Uploaded by

kfakeid9
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 24

qn1

import java.util.Scanner;

public class PalindromeChecker {


public static boolean isPalindrome(String s) {
s = s.toLowerCase().replaceAll("[^a-z0-9]", "");
int i = 0, j = s.length() - 1;
while (i < j) {
if (s.charAt(i) != s.charAt(j)) {
return false;
}
i++;
j--;
}
return true;
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
System.out.println(isPalindrome(input));
scanner.close();
}
}

##

wcc-1-1

import java.util.Scanner;

public class Solution {


public int singleNumber(int[] nums) {
int t=0;
for(int i=0;i<nums.length;i++)
{
t^=nums[i];
}
return t;
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

// System.out.println("Enter the numbers separated by spaces:");


String input = scanner.nextLine(); // Get input as a single line
String[] inputArray = input.split(" "); // Split the input string by spaces

int[] nums = new int[inputArray.length];


for (int i = 0; i < inputArray.length; i++) {
nums[i] = Integer.parseInt(inputArray[i]); // Convert each value to an
integer
}

Solution solution = new Solution();


int result = solution.singleNumber(nums);
System.out.println(result);
}
}

##

wcc-4-hard

import java.util.*;

class Solution {

public int firstMissingPositive(int[] nums) {


int[] filterednums = Arrays.stream(nums).filter(n-> n > 0).toArray();
Arrays.sort(filterednums);
int target=1;
for(int n : filterednums)
{
if(n==target)
{
target++;
}
else if(n>target)
{
return target;
}
}
return target;
}
}
public class Main
{

public static void main(String[] args) {


Solution solution = new Solution();
Scanner scanner = new Scanner(System.in);

// Input the size of the array

int n = scanner.nextInt();

// Input the array elements


int[] nums = new int[n];

for (int i = 0; i < n; i++) {


nums[i] = scanner.nextInt();
}

// Find the smallest missing positive integer


int result = solution.firstMissingPositive(nums);
System.out.println("The smallest missing positive integer is: " + result);
}
}

##

wcc-5-hard
import java.util.*;
import java.util.Stack;
public class Solution {
public int calculate(String s) {
Stack<Integer> stack = new Stack<>();
int ans = 0;
int num = 0;
int sign = 1;

for (int i = 0; i < s.length(); i++) {


char ch = s.charAt(i);

if (Character.isDigit(ch)) {
num = num * 10 + (ch - '0');
} else if (ch == '+' || ch == '-') {
ans += num * sign;
num = 0;
sign = (ch == '-') ? -1 : 1;
} else if (ch == '(') {
stack.push(ans);
stack.push(sign);
ans = 0;
sign = 1;
} else if (ch == ')') {
ans += num * sign;
ans *= stack.pop(); // sign before '('
ans += stack.pop(); // result before '('
num = 0;
}
}

ans += num * sign;


return ans;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

String input = scanner.nextLine();

// Create an instance of Solution and process the input


Solution solution = new Solution();
int result = solution.calculate(input);

System.out.println(result);

scanner.close();
}
}

##

wcc-7-hard

import java.util.*;

public class Solution {


public int maxProfit(int[] prices) {
int sell1 = 0, sell2 = 0, buy1 = Integer.MIN_VALUE, buy2 =
Integer.MIN_VALUE;
for (int i = 0; i < prices.length; i++) {
buy1 = Math.max(buy1, -prices[i]);
sell1 = Math.max(sell1, buy1 + prices[i]);
buy2 = Math.max(buy2, sell1 - prices[i]);
sell2 = Math.max(sell2, buy2 + prices[i]);
}
return sell2;
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

// Read the number of days (size of the prices array)


//System.out.print("Enter the number of days: ");
int n = scanner.nextInt();

// Read the stock prices for each day


int[] prices = new int[n];
//System.out.print("Enter the stock prices (space-separated): ");
for (int i = 0; i < n; i++) {
prices[i] = scanner.nextInt();
}

// Create an object of the Solution class


Solution solution = new Solution();

// Calculate and print the maximum profit


int maxProfit = solution.maxProfit(prices);
System.out.println(maxProfit);

// Close the scanner


scanner.close();
}
}

##

wcc-8-easy

import java.util.*;
public class Solution {
public int climbStairs(int n) {
if (n <= 3) return n;

int prev1 = 3;
int prev2 = 2;
int cur = 0;

for (int i = 3; i < n; i++) {


cur = prev1 + prev2;
prev2 = prev1;
prev1 = cur;
}

return cur;
}
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
Solution sol = new Solution();

int n = sc.nextInt();

System.out.println(sol.climbStairs(n));

sc.close();
}
}

##

wcc-8-med

import java.util.*;
public class Solution {
public int maxSubArray(int[] nums) {
int res = nums[0];
int total = 0;

for (int n : nums) {


if (total < 0) {
total = 0;
}

total += n;
res = Math.max(res, total);
}

return res;
}

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);

String input = sc.nextLine();


String[] inputArray = input.split(" ");

int[] nums = new int[inputArray.length];

for (int i = 0; i < inputArray.length; i++) {


nums[i] = Integer.parseInt(inputArray[i]);
}

Solution sol = new Solution();

System.out.println( sol.maxSubArray(nums));

sc.close();
}
}

##

wcc-8-hard
import java.util.*;
public class Solution {
public int maxPoints(int[][] points) {
int n = points.length;
if(n <= 2) return n; // 2 or less points can always form a line.
int ans = 2;

for(int[] a : points){
//Map<Double, Integer> for storing (slope, no of times 2 points
generate this slope.)
Map<Double, Integer> map = new HashMap<>();
for(int[] b : points){
if(a == b) continue; // dont measure slope for same points in
plane.
// if a is (x1, y1) and b is(x2, y2) then slope is (y2 - y1)/(x2 -
x1)
// a (a0, a1) & b is (b0, b1)
double slope = 0;
if(b[0] - a[0] == 0) slope = Double.POSITIVE_INFINITY;
else slope = (b[1] -a[1]) / (double)(b[0] - a[0]);
//map.getOrDefault(slope, 0)+1 is adding 1 more point count for
that slope if we already had that slope.
// by default , 1 will be count of a new slope.
map.put(slope, map.getOrDefault(slope, 1)+1);
ans = Math.max(ans, map.get(slope));
}
}
//ans itself represnets max no of points forms a line
return ans;
}

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);

int n = sc.nextInt();
int[][] points = new int[n][2];

for (int i = 0; i < n; i++) {


points[i][0] = sc.nextInt();
points[i][1] = sc.nextInt();
}

Solution sol = new Solution();

System.out.println(sol.maxPoints(points));

sc.close();
}
}

##

wcc-9-easy

import java.util.*;
public class Solution {
public int[] plusOne(int[] digits) {
for (int i = digits.length - 1; i >= 0; i--) {
if (digits[i] + 1 != 10) {
digits[i] += 1;
return digits;
}
digits[i] = 0;
}

int[] newDigits = new int[digits.length + 1];


newDigits[0] = 1;
return newDigits;
}

public static void main(String[] args)


{
Scanner scanner = new Scanner(System.in);

String[] input = scanner.nextLine().split(" ");

int[] digits = new int[input.length];


for (int i = 0; i < input.length; i++)
{
digits[i] = Integer.parseInt(input[i]);
}

Solution solution = new Solution();


int[] result = solution.plusOne(digits);

System.out.print("[");
for (int i = 0; i < result.length; i++)
{
System.out.print(result[i]);
if (i < result.length - 1)
{
System.out.print(",");
}
}
System.out.println("]");

scanner.close();
}
}

##

wcc-9-med

import java.util.ArrayList;
import java.util.List;
import java.util.*;
public class Solution {
public int countPrimes(int n) {
if(n <= 2) return 0;

boolean[] isPrime = new boolean[n];


Arrays.fill(isPrime, true);

isPrime[0] = false;
isPrime[1] = false;
for(int i = 2; i * i < n; i++){
if(isPrime[i]){
for(int j = i * i; j < n; j += i){
isPrime[j] = false;
}
}
}
int cnt = 0;
for(boolean prime: isPrime){
if(prime){
cnt++;
}
}
return cnt;
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);
//System.out.print("Enter a number: ");
int n = scanner.nextInt(); // Read user input
scanner.close();

Solution sol = new Solution();


System.out.println( sol.countPrimes(n));
}
}

##

wcc-9-hard

import java.util.*;
import java.util.regex.*;
enum Result {
TRUE, FALSE
}

public class Solution {


Result[][] memo;

public boolean isMatch(String text, String pattern) {


memo = new Result[text.length() + 1][pattern.length() + 1];
return dp(0, 0, text, pattern);
}

public boolean dp(int i, int j, String text, String pattern) {


if (memo[i][j] != null) {
return memo[i][j] == Result.TRUE;
}
boolean ans;
if (j == pattern.length()){
ans = i == text.length();
} else{
boolean first_match = (i < text.length() &&
(pattern.charAt(j) == text.charAt(i) ||
pattern.charAt(j) == '.'));

if (j + 1 < pattern.length() && pattern.charAt(j+1) == '*'){


ans = (dp(i, j+2, text, pattern) ||
first_match && dp(i+1, j, text, pattern));
} else {
ans = first_match && dp(i+1, j+1, text, pattern);
}
}
memo[i][j] = ans ? Result.TRUE : Result.FALSE;
return ans;
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

// Get input string and pattern from user


//System.out.print("Enter string s: ");
String s = scanner.nextLine();

//System.out.print("Enter pattern p: ");


String p = scanner.nextLine();

Solution sol = new Solution();

// Print the result


System.out.println(sol.isMatch(s, p));

scanner.close();
}
}

##

wcc-10-easy

import java.util.*;
public class Solution {
public boolean isAnagram(String s, String t) {
if (s.length() != t.length()) {
return false;
}

Map<Character, Integer> counter = new HashMap<>();

for (int i = 0; i < s.length(); i++) {


char ch = s.charAt(i);
counter.put(ch, counter.getOrDefault(ch, 0) + 1);
}

for (int i = 0; i < t.length(); i++) {


char ch = t.charAt(i);
if (!counter.containsKey(ch) || counter.get(ch) == 0) {
return false;
}
counter.put(ch, counter.get(ch) - 1);
}

return true;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String s = scanner.next().toLowerCase(); // Convert to lowercase for
consistency

String t = scanner.next().toLowerCase();

Solution solution = new Solution();


boolean result = solution.isAnagram(s, t);

// Print result
System.out.println(result);

scanner.close();
}
}

##

wcc-10-med

import java.util.*;
public class Solution {
public int[] productExceptSelf(int[] nums) {
int[] output = new int[nums.length];
for (int i = 0; i < nums.length; i++) {
output[i] = 1;
}

int left = 1;
for (int i = 0; i < nums.length; i++) {
output[i] *= left;
left *= nums[i];
}

int right = 1;
for (int i = nums.length - 1; i >= 0; i--) {
output[i] *= right;
right *= nums[i];
}

return output;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Get input size
int n = scanner.nextInt();

// Get input array


int[] nums = new int[n];

for (int i = 0; i < n; i++) {


nums[i] = scanner.nextInt();
}

Solution solution = new Solution();


int[] result = solution.productExceptSelf(nums);

// Display the result


for (int num : result) {
System.out.print(num + " ");
}

scanner.close();
}
}

##

wcc-10-hard

import java.util.*;
public class Solution {
public String numberToWords(int num) {
if(num == 0)
return "Zero";
String[] bigString = new String[]{"Thousand","Million","Billion"};
String result = numberToWordsHelper(num%1000);
num = num/1000;
if(num > 0 && num%1000>0){
result = numberToWordsHelper(num%1000) + "Thousand " + result;
}
num = num/1000;
if(num > 0 && num%1000>0){
result = numberToWordsHelper(num%1000) + "Million " + result;
}
num = num/1000;
if(num > 0){
result = numberToWordsHelper(num%1000) + "Billion " + result;
}
return result.trim();
}

public String numberToWordsHelper(int num){


String[] digitString = new String[]{"Zero", "One", "Two", "Three", "Four",
"Five", "Six", "Seven", "Eight", "Nine"};
String[] teenString = new String[]{"Ten", "Eleven", "Twelve", "Thirteen",
"Fourteen", "Fifteen", "Sixteen", "Seventeen","Eighteen", "Nineteen"};
String[] tenString = new String[]{"","","Twenty", "Thirty", "Forty", "Fifty",
"Sixty", "Seventy", "Eighty", "Ninety"};
String result = "";
if(num > 99){
result += digitString[num/100] + " Hundred ";
}
num = num % 100;
if(num < 20 && num > 9){
result += teenString[num%10]+" ";
}else{
if(num > 19){
result += tenString[num/10]+" ";
}
num = num % 10;
if(num > 0)
result += digitString[num]+" ";
}
return result;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int num = scanner.nextInt();

// Convert number to words


Solution solution = new Solution();
String result = solution.numberToWords(num);

// Display the output


System.out.println(result);

scanner.close();
}
}

##

wcc-11-easy

import java.util.*;

public class Solution {


public int lengthOfLastWord(String s) {
int end = s.length() - 1;

while (end >= 0 && s.charAt(end) == ' ') {


end--;
}

int start = end;


while (start >= 0 && s.charAt(start) != ' ') {
start--;
}

return end - start;


}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

String input = scanner.nextLine();

// Create Solution object and call the method


Solution solution = new Solution();
int length = solution.lengthOfLastWord(input);

// Print the result


System.out.println(length);

}
}

##

wcc-11-med

import java.util.*;
import java.util.Arrays;

public class Solution {


public void sortColors(int[] nums) {
HashMap<Integer, Integer> count = new HashMap<>();
count.put(0, 0);
count.put(1, 0);
count.put(2, 0);

for (int num : nums) {


count.put(num, count.get(num) + 1);
}

int idx = 0;
for (int color = 0; color < 3; color++) {
int freq = count.get(color);
for (int j = 0; j < freq; j++) {
nums[idx] = color;
idx++;
}
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Take input array size


//System.out.print("Enter number of elements: ");
int n = scanner.nextInt();
int[] nums = new int[n];

// Take array elements as input


//System.out.println("Enter elements (only 0, 1, or 2): ");
for (int i = 0; i < n; i++) {
nums[i] = scanner.nextInt();
}

// Sort colors
Solution solution = new Solution();
solution.sortColors(nums);

// Print the sorted array


System.out.println(Arrays.toString(nums));

}
}

##

wcc-11-hard

import java.util.*;

public class Solution {


public int candy(int[] ratings) {
int n = ratings.length;
int cnt = 0;
int[] candies = new int[n];
for (int i = 0; i < n; i++) candies[i] = 1;
for (int i = 1; i < n; i++)
if (ratings[i] > ratings[i - 1])
candies[i] = candies[i - 1] + 1;
for (int i = n - 1; i > 0; i--) {
if (ratings[i - 1] > ratings[i])
candies[i - 1] = Math.max(candies[i] + 1, candies[i - 1]);
cnt += candies[i - 1];
}
return cnt + candies[n - 1];
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Taking runtime input


//System.out.print("Enter number of children: ");
int n = scanner.nextInt();
int[] ratings = new int[n];

// System.out.println("Enter ratings of children:");


for (int i = 0; i < n; i++) {
ratings[i] = scanner.nextInt();
}

Solution solution = new Solution();


int result = solution.candy(ratings);

System.out.println(result);
scanner.close();
}
}

##

wcc-12-easy

import java.util.*;

public class Solution {


public int searchInsert(int[] nums, int target) {
int left = 0;
int right = nums.length - 1;

while (left <= right) {


int mid = left + (right - left) / 2;

if (nums[mid] == target) {
return mid;
} else if (nums[mid] > target) {
right = mid - 1;
} else {
left = mid + 1;
}
}

return left;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Taking runtime input for the array


//System.out.print("Enter number of elements: ");
int n = scanner.nextInt();
int[] nums = new int[n];

//System.out.println("Enter sorted array elements:");


for (int i = 0; i < n; i++) {
nums[i] = scanner.nextInt();
}

// Taking runtime input for the target value


//System.out.print("Enter target value: ");
int target = scanner.nextInt();

Solution solution = new Solution();


int result = solution.searchInsert(nums, target);

System.out.println(result);
scanner.close();
}
}

##

wcc-12-med

import java.util.Arrays;
import java.util.*;

public class Solution {


public int coinChange(int[] coins, int amount) {
int[] minCoins = new int[amount + 1];
Arrays.fill(minCoins, amount + 1);
minCoins[0] = 0;

for (int i = 1; i <= amount; i++) {


for (int j = 0; j < coins.length; j++) {
if (i - coins[j] >= 0) {
minCoins[i] = Math.min(minCoins[i], 1 + minCoins[i -
coins[j]]);
}
}
}

return minCoins[amount] != amount + 1 ? minCoins[amount] : -1;


}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// User input for coin denominations


//System.out.println("Enter the number of coins:");
int n = scanner.nextInt();
int[] coins = new int[n];

//System.out.println("Enter the coin values:");


for (int i = 0; i < n; i++) {
coins[i] = scanner.nextInt();
}

// User input for amount


//System.out.println("Enter the amount:");
int amount = scanner.nextInt();

Solution solution = new Solution();


int result = solution.coinChange(coins, amount);
System.out.println(result);
}
}

##

wcc-12-hard

import java.util.*;

public class Solution {


public List<String> findAllConcatenatedWordsInADict(String[] words) {
Set<String> s = new HashSet<>();
List<String> concatenateWords = new ArrayList<>();
for(String word : words)
s.add(word);
for(String word : words) {
if(checkConcatenate(word, s) == true)
concatenateWords.add(word);
}
return concatenateWords;
}
public boolean checkConcatenate(String word, Set<String> s) {
for(int i = 1; i < word.length(); i++) {
String prefixWord = word.substring(0, i);
String suffixWord = word.substring(i, word.length());
if(s.contains(prefixWord) && (s.contains(suffixWord) ||
checkConcatenate(suffixWord, s)))
return true;
}
return false;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Take input for the number of words


//System.out.println("Enter the number of words:");
int n = scanner.nextInt();
scanner.nextLine(); // Consume newline character

// Take input for words


String[] words = new String[n];
//System.out.println("Enter the words:");
for (int i = 0; i < n; i++) {
words[i] = scanner.nextLine();
}

// Process the input and find concatenated words


Solution solution = new Solution();
List<String> result = solution.findAllConcatenatedWordsInADict(words);

// Print output in the desired format with double quotes


//System.out.println("Output:");
System.out.print("[");
for (int i = 0; i < result.size(); i++) {
System.out.print("\"" + result.get(i) + "\"");
if (i < result.size() - 1) {
System.out.print(", ");
}
}
System.out.println("]");

scanner.close();
}
}

##

wcc-13-easy

import java.util.*;

public class Solution {


public boolean hasMatch(String s, String p) {
int index = p.indexOf('*');
int firstpos = s.indexOf(p.substring(0, index));
int secondpos = s.indexOf(p.substring(index + 1), firstpos + index);
if (firstpos != -1 && secondpos != -1) {
return true;
}
return false;
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

// Take input for the string s and the pattern p


//System.out.println("Enter the string s:");
String s = scanner.nextLine();

//System.out.println("Enter the pattern p (with exactly one '*'):");


String p = scanner.nextLine();

// Process the input and check if the pattern can be a substring


Solution solution = new Solution();
boolean result = solution.hasMatch(s, p);

// Print the output based on the result


if (result) {
System.out.println("true");
} else {
System.out.println("false");
}

scanner.close();
}
}

##

wcc-13-med

import java.util.*;

public class Solution {


public void rotate(int[] nums, int k) {
k %= nums.length;
reverse(nums, 0, nums.length - 1);
reverse(nums, 0, k - 1);
reverse(nums, k, nums.length - 1);
}

private void reverse(int[] nums, int left, int right) {


while (left < right) {
int temp = nums[left];
nums[left] = nums[right];
nums[right] = temp;
left++;
right--;
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Input for the array size and the array elements


//System.out.println("Enter the size of the array:");
int n = scanner.nextInt();

int[] nums = new int[n];

//System.out.println("Enter the elements of the array:");


for (int i = 0; i < n; i++) {
nums[i] = scanner.nextInt();
}

// Input for the number of rotations


//System.out.println("Enter the number of rotations (k):");
int k = scanner.nextInt();

// Create Solution object and rotate the array


Solution solution = new Solution();
solution.rotate(nums, k);

// Print the rotated array


//System.out.println("Rotated Array:");
for (int num : nums) {
System.out.print(num + " ");
}

scanner.close();
}
}

##

wcc-13-hard

import java.util.*;

public class Solution {


public boolean isNumber(String s) {
boolean isdot = false, ise = false, nums = false;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (Character.isDigit(c)) nums = true;
else if (c == '+' || c == '-') {
if (i > 0 && s.charAt(i - 1) != 'e' && s.charAt(i - 1) != 'E')
return false;
}
else if (c == 'e' || c == 'E') {
if (ise || !nums) return false;
ise = true;
nums = false;
}
else if (c == '.') {
if (isdot || ise) return false;
isdot = true;
}
else return false;
}
return nums;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Input string to be checked


//System.out.println("Enter a string to check if it's a valid number:");
String input = scanner.nextLine();

// Create Solution object and check the input string


Solution solution = new Solution();
boolean result = solution.isNumber(input);

// Output result
if (result) {
System.out.println("true");
} else {
System.out.println("false");
}

scanner.close();
}
}

##

wcc-14-easy

import java.util.*;

public class Solution {


public int findMaxConsecutiveOnes(int[] nums) {
int res = 0;
int count = 0;

for (int n : nums) {


if (n == 0) {
count = 0;
} else {
count++;
}

if (res < count) {


res = count;
}
}

return res;
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

String input = scanner.nextLine();


String[] inputStrings = input.split(" ");
int[] nums = new int[inputStrings.length];

for (int i = 0; i < inputStrings.length; i++) {


nums[i] = Integer.parseInt(inputStrings[i]);
}

Solution solution = new Solution();

int result = solution.findMaxConsecutiveOnes(nums);

System.out.println(result);

scanner.close();
}
}

##

wcc-14-med

import java.util.*;

public class Solution {


public int maxProduct(int[] nums) {
int res = Integer.MIN_VALUE;
for (int n : nums) {
res = Math.max(res, n);
}

int curMax = 1, curMin = 1;

for (int n : nums) {


int temp = curMax * n;
curMax = Math.max(temp, Math.max(curMin * n, n));
curMin = Math.min(temp, Math.min(curMin * n, n));

res = Math.max(res, curMax);


}

return res;
}
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);

String input = scanner.nextLine();


String[] inputStrings = input.split(" ");
int[] nums = new int[inputStrings.length];

for (int i = 0; i < inputStrings.length; i++)


{
nums[i] = Integer.parseInt(inputStrings[i]);
}

Solution solution = new Solution();

int result = solution.maxProduct(nums);

System.out.println(result);

scanner.close();
}

##

wcc-14-hard

import java.util.*;

public class Solution {


public int longestValidParentheses(String s) {
Stack<Integer> stack = new Stack<>();
stack.push(-1);
int max_len = 0;

for (int i = 0; i < s.length(); i++) {


if (s.charAt(i) == '(') {
stack.push(i);
} else {
stack.pop();
if (stack.isEmpty()) {
stack.push(i);
} else {
max_len = Math.max(max_len, i - stack.peek());
}
}
}

return max_len;
}

public static void main(String[] args) {


Solution solution = new Solution();
java.util.Scanner scanner = new java.util.Scanner(System.in);
String s = scanner.nextLine().trim();
int result = solution.longestValidParentheses(s);
System.out.println(result);
scanner.close();
}
}

##

wcc-15-easy
import java.util.*;

public class Solution {


public List<Boolean>kidsWithcandies(int[] candies, int extraCandies) {
int maxCandies = 0;
for (int candy : candies) {
maxCandies = Math.max(maxCandies, candy);
}

List<Boolean> result = new ArrayList<>();

for (int candy : candies) {


if (candy + extraCandies >= maxCandies) {
result.add(true);
} else {
result.add(false);
}
}

return result;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

int n = scanner.nextInt();

int[] candies = new int[n];

for (int i = 0; i < n; i++) {


candies[i] = scanner.nextInt();
}

int extraCandies = scanner.nextInt();

// Compute the result


Solution sol = new Solution();
List<Boolean> result = sol.kidsWithcandies(candies, extraCandies);

// Display the result


System.out.println(result);

scanner.close();
}
}

##

wcc-15-med

import java.util.Scanner;

public class Solution {


public int longestCommonSubsequence(String text1, String text2) {
int[] dp = new int[text1.length()];
int longest = 0;

for (char c : text2.toCharArray()) {


int curLength = 0;
for (int i = 0; i < dp.length; i++) {
if (curLength < dp[i]) {
curLength = dp[i];
} else if (c == text1.charAt(i)) {
dp[i] = curLength + 1;
longest = Math.max(longest, curLength + 1);
}
}
}

return longest;
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

String text1 = scanner.nextLine();

String text2 = scanner.nextLine();


Solution sol = new Solution();
// Compute and display the LCS length
int result = sol.longestCommonSubsequence(text1, text2);
System.out.println(result);

scanner.close();
}
}

##

wcc-15-hard

import java.util.*;
public class Solution {
public int numDistinct(String s, String t) {
int m = s.length(), n = t.length();
int[][] dp = new int[m + 1][n + 1];
for(int i = 0; i < m; i ++){
dp[i][0] = 1;
}
for(int i = 1; i <= m; i ++){
for(int j = 1; j <= n; j ++){
if(s.charAt(i - 1) == t.charAt(j - 1)){
dp[i][j] = dp[i - 1][j - 1] + dp[i - 1][j];
}else{
dp[i][j] = dp[i - 1][j];
}
}
}
return dp[m][n];
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

String s = scanner.nextLine();

String t = scanner.nextLine();
Solution solution = new Solution();
int result = solution.numDistinct(s, t);

System.out.println(result);

scanner.close();
}
}

You might also like