You are on page 1of 21

Length of longest decreasing subsequence in an array

public static void getDecSeq(int[] data) {


int currentSeq = 1;
int currentIndex = 1;

int longestSeq = 0;
int longestIndex = 0;
for (int i = currentIndex; i < data.length; i++) {
if (data[i] < data[i - 1]) {
currentSeq++;
} else {
currentSeq = 1;
currentIndex = i;
}
if (currentSeq > longestSeq) {
longestSeq = currentSeq;
longestIndex = currentIndex;
}
//double[] sequence = new double[longestSeq];
//for (int j = longestIndex; j < longestSeq; j++) {
//sequence[j] //}
}
output1= longestSeq;
}
when we give input
0,10,8,31,2
the output is 2
public static void getDecSeq(int[] data) {
int currentSeq = 1;
int currentIndex = 1;

int longestSeq = 0;
int longestIndex = 0;
for (int i = currentIndex; i < data.length; i++) {
if (data[i] < data[i - 1]) {
currentSeq++;
} else {
currentSeq = 1;
currentIndex = i;
}
if (currentSeq > longestSeq) {
longestSeq = currentSeq;
longestIndex = currentIndex;
}
//double[] sequence = new double[longestSeq];
//for (int j = longestIndex; j < longestSeq; j++) {
//sequence[j]
//}
}
output1= longestSeq;
}
Length of longest increasing subsequence in an array

ANS 1)public static void printLIS(int[] nums)
{
String paths[]=new String[nums.length];
int sizes[]=new int[nums.length];
for(int i=0;i<nums.length;i++)
{
sizes[i]=1;
paths[i]=nums[i]+" ";
}
int output1=1;
for(int i=1;i<nums.length;i++)
for(int j=0;j<i;j++)
{
if(nums[i]>nums[j] && sizes[i]<sizes[j]+1)
{
sizes[i]=sizes[j]+1;
paths[i]=paths[j]+nums[i]+" ";
if(output1<sizes[i])
output1=sizes[i];
}
}
import java.util.*;
public class LIC
{
public static void main(String args[])
{
System.out.println("Enter size");
Scanner Scn=new Scanner(System.in);
int n=Scn.nextInt();
int nums[]=new int[n];
System.out.println("Enter array ");
for(int i=0;i<n;i++)
nums[i]=Scn.nextInt();
printLIS(nums);

}
public static void printLIS(int[] nums)
{
String paths[]=new String[nums.length];
int sizes[]=new int[nums.length];
for(int i=0;i<nums.length;i++)
{
sizes[i]=1;
paths[i]=nums[i]+" ";
}
int maxlength=1;
for(int i=1;i<nums.length;i++)
for(int j=0;j<i;j++)
{
if(nums[i]>nums[j] && sizes[i]<sizes[j]+1)
{
sizes[i]=sizes[j]+1;
paths[i]=paths[j]+nums[i]+" ";
if(maxlength<sizes[i])
maxlength=sizes[i];
}
}
for(int i=1;i<nums.length;i++)
{if(sizes[i]==maxlength)
System.out.println("LIS: "+paths[i]);
}
}
}
N is an integer (1<N<=100) representing number of persons
names[ ] - array os strings , names of N persons
for 0<+i<N , names{i} is the name of ith person 1<=len(names[i])<=10 and names
consist of only lowercase alphabets.
M is an integer(1<=M<=1000) representing number of exchange from [ ] - names of
lenders(string array) to [ ] - names of borrowers , amount [ ] - an array of integers -
amt of money borrowed ( i <= amt[i]<=1000)
for 0<=i<M , from [i] lends amt[i] to [i]
figure out the amount of money they had after sequence of sendings.
I/p is 2{x,y} 1{x{y}} {100}
O/p is {-100,100}
class ______
{
public static int[] output1;

public static void _____(int input1, string[] input2, int input3, string[] input4, string[] input5, int[] input6)
{
//code starts from here
int[] output1 = new int[input1];

for(int i = 0; i < input1; i++)
{
output1[i] = 0;
}

for(int i = 0; i < input3; i++)
{
string FROM = input4[i];
int AMOUNT = input6[i];
string TO = input5[i];
for(int j = 0; j < input1; j++)
{
if(input2[j] == FROM)
{
output1[j] -= AMOUNT;
}
if(input2[j] == TO)
{
output1[j] += AMOUNT;
}
}
}

}
}
Dice Question
int findWays(int m, int n, int x)
{

int table[n + 1][x + 1];
memset(table, 0, sizeof(table)); // Initialize all entries as 0

// Table entries for only one dice
for (int j = 1; j <= m && j <= x; j++)
table[1][j] = 1;

// Fill rest of the entries in table using recursive relation
// i: number of dice, j: sum
for (int i = 2; i <= n; i++)
for (int j = 1; j <= x; j++)
for (int k = 1; k <= m && k < j; k++)
table[i][j] += table[i-1][j-k];
output1=table[n][x];return output1;
}

int findWays(int m, int n, int x)
{

int table[n + 1][x + 1];
memset(table, 0, sizeof(table)); // Initialize all entries as 0

// Table entries for only one dice
for (int j = 1; j <= m && j <= x; j++)
table[1][j] = 1;

// Fill rest of the entries in table using recursive relation
// i: number of dice, j: sum
for (int i = 2; i <= n; i++)
for (int j = 1; j <= x; j++)
for (int k = 1; k <= m && k < j; k++)
table[i][j] += table[i-1][j-k];
output1=table[n][x];return output1;
}
Find the shortest substring that is having minimum distance in the string
having all the characters in the given word
Input my name is khan
Search string him
Output me is kh

public class substr_min_dist
{

public static void main(String[] args)
{
String output = minWindow("my name is khan", "him");
System.out.println("min window is :::" + output);
}

public static String minWindow(String S, String T)
{
int[] needToFind = new int[256];
int[] hasFound = new int[256];

for (int i = 0; i < T.length(); ++i)
{
needToFind[T.charAt(i)]++;
}

int count = 0;
int minWindowSize = Integer.MAX_VALUE;
int start = 0, end = 0;
String window = "";

for (; end < S.length(); end++)
{
if (needToFind[S.charAt(end)] == 0)
{
continue;
}
char c = S.charAt(end);
hasFound[c]++;

if (hasFound[c] <= needToFind[c])
{
count++;
}

if (count == T.length())
{
while (needToFind[S.charAt(start)] == 0
|| hasFound[S.charAt(start)] > needToFind[S.charAt(start)])
{
if (hasFound[S.charAt(start)] > needToFind[S.charAt(start)])
{
hasFound[S.charAt(start)]--;
}
start++;
}

if (end - start + 1 < minWindowSize)
{
minWindowSize = end - start + 1;
window = S.substring(start, end + 1);
}
}
}

return window;
}
}
inversion count program in java
public class inversecount {
public static void getInvCount(int arr[], int n)
{
int inv_count = 0;
int i, j;

for(i = 0; i < n - 1; i++)
for(j = i+1; j < n; j++)
if(arr[i] > arr[j])
inv_count++;

System.out.print(inv_count);
}

public static void main(String[] args)
{
int arr[] = {3,2,1};
getInvCount(arr,3);
}
}
To find the factorial of a number:
The formula is (n+r-1) C (r-1) which is equal to: numerator= (n+r-1) factorial denominator= (r-1)
factorial * (n) factorial

Use the code:
//To find the factorial of "n"
result=1;
for(i=1;i<=n;i++)
result*=i
Distribution of n things among r people.
import java.math.*;

public class InvMod
{
public static void main(String args[])
{
int x=2;
long y=x;
long m=1000000007;
y=y%m;
long i=0;

for(i=0;i<m;i++)
{
if((y*i)%m==1)
break;
}
int out=(int)i;
System.out.println(out);

}
}
Modular Exponention
given number b, e and m(1<=b,e,m<=10^9), output(b^e) mod m
Aditi Sharma import java.util.Scanner;
import java.lang.*;
class modular{
public static void main(String[] args)
{

Scanner s=new Scanner(System.in);
System.out.println("enter the value of a");
int x=s.nextInt();

System.out.println("enter the value of b");
int y=s.nextInt();

System.out.println("enter the value of c");

int z=s.nextInt();

double w=Math.pow(x,y);
int e=(int)w;
System.out.println(e);
int f=e % z;
System.out.println(f);

}
}
Postfix volution:
Find a function which takes as input string containing a postfix exprsn and sets of the
output variable to its evaluation.
String s = "74*3+4-5+";

int i=0, result=0;
int a[] = new int[2];

for(char c : s.toCharArray()) {
System.out.println("1 : " + a[0] + " 2 : " + a[1]);
if(Character.isDigit(c)) {
a[i] = Integer.parseInt(String.valueOf(c));
i= (i+1)%2;
}
else {
switch(c) {

case '+': result = a[0]+a[1];
break;
case '-': result = a[0]-a[1];
break;
case '*': result = a[0]*a[1];
break;
case '/': result = a[0]/a[1];
break;
}
a[0] = result;
i= (i+1)%2;
}
}
result = a[0];
System.out.println(result);
Evaluation of postfix expression java
import java.io.*;
class Stack
{
private int[] a;
private int top,m;
public Stack(int max)
{
m=max;
a=new int[m];
top=-1;
}
public void push(int key)
{
a[++top]=key;
}
public int pop()
{
return(a[top--]);
}
}
class Evaluation{
public int calculate(String s)
{
int n,r=0;
n=s.length();
Stack a=new Stack(n);
for(int i=0;i<n;i++)
{
char ch=s.charAt(i);
if(ch>='0'&&ch<='9')
a.push((int)(ch-'0'));
else
{
int x=a.pop();
int y=a.pop();
switch(ch)
{
case '+':r=x+y;
break;
case '-':r=y-x;
break;
case '*':r=x*y;
break;
case '/':r=y/x;
break;
default:r=0;
}
a.push(r);
}
}
r=a.pop();
return(r);
}
}
class PostfixEvaluation
{
public static void main(String[] args)throws IOException
{
String input;
while(true)
{
System.out.println("Enter the postfix expresion");
input=getString();
if(input.equals(""))
break;
Evaluation e=new Evaluation();
System.out.println("Result:- "+e.calculate(input));
}
}
public static String getString()throws IOException
{
DataInputStream inp=new DataInputStream(System.in);
String s=inp.readLine();
return s;
}
}
Evaluation of prefix expression java
import java.util.*;
class PrefixEvaluate
{
static int top=-1;
static String exp;
static String[] op=new String[100];
static int a,b;
public static void main(String args[])
{
String ch="";
int i;
Scanner sc=new Scanner(System.in);
System.out.println("enter the prefix expression");
exp=sc.next();
op[++top]=")";
for(i=exp.length()-1;i>=0;i--)
{
ch=String.valueOf(exp.charAt(i));
switch(ch)
{
case "0": case "1": case "2": case "3": case "4": case "5": case "6": case "7": case "8": case "9":
push(ch);
break;
case "^": case "+": case "-": case "*": case "/":
a=Integer.valueOf(pop());
b=Integer.valueOf(pop());
if (ch.equals("^"))
push(String.valueOf((int)Math.pow(a,b)));
else if (ch.equals("+"))
push(String.valueOf(a+b));
else if (ch.equals("-"))
push(String.valueOf(a-b));
else if (ch.equals("*"))
push(String.valueOf(a*b));
else if (ch.equals("/"))
push(String.valueOf(a/b));
break;
}
System.out.println("top element"+op[top]);
}

}
static void push(String ch)
{
op[++top]=String.valueOf(ch);
}
static String pop()
{
String c;
c=op[top];
top--;
return c;
}
}
Infix to Postfix Conversion
import java.io.*;
import java.lang.*;
class stack
{
private final int STACKSIZE=50;
private int top;
private char items[];
public stack()
{
top=-1;
items=new char[STACKSIZE];
}
public void push(char a)
{
if (top==STACKSIZE-1)
{
System.out.println("overflow");
return;
}
else
top++;
items[top]=a;
}
public boolean isEmpty()
{
if(top==-1)
return true;
else
return false;
}
public char pop()
{
if (top==-1)
{
System.out.print("empty, cannot pop");
return ' ';
}
return(items[top--]);
}
public char peek()
{
if (top==-1)
{
System.out.println("empty, can not peek");
return ' ';
}
return(items[top]);
}
public void display()
{
for(int i=top;i>=0;i--)
System.out.println(items[i]);
}
}
class Infix2Postfix
{
private boolean isOpenBracket(char m)
{
if(m=='(')
return true;
else
return false;
}
private boolean isOperator(char m)
{
if(m=='+'||m=='-'||m=='/'||m=='*')
return true;
else
return false;
}
private boolean isOperand(char m)
{
if((m>='0'&& m<='9') || (m >= 'a' && m<= 'z') || (m >='A' && m<='Z'))
return true;
else
return false;
}
private int priority(char ch)
{
int priority;
priority=0;;
switch (ch)
{
case'+': priority=3;
break;
case'-': priority=2;
break;
case'*': priority=5;
break;
case'/': priority=4;
break;
case'%': priority=1;
break;
}
return priority;
}
public void convert(String str)
{
char ch;
stack s=new stack();
int i,j;
j=0;
char postfix[] = new char[str.length()];
for(i=0;i<str.length();i++)
{
ch=str.charAt(i);
if(isOpenBracket(ch))
s.push(ch);
else if (isOperand(ch))
postfix[j++]=ch;
else if (isOperator(ch))
if (s.isEmpty())
s.push(ch);
else
{
if (priority(ch) >= priority(s.peek()))
s.push(ch);
else
{
while (priority(ch) < priority(s.peek()))
postfix[j++]=s.pop();
s.push(ch);
}
}
else if (!isOpenBracket(ch))
{
while (!isOpenBracket(s.peek()))
postfix[j++]=s.pop();
if (isOpenBracket(s.peek()))
s.pop();
}
}
while(!s.isEmpty())
{
postfix[j++]=s.pop();
}
for(i=0;i<str.length();i++)
System.out.print(postfix[i]);
}
}
public class Infixtopostfix
{
public static void main(String[] args) throws IOException
{
String str;
Infix2Postfix in2post = new Infix2Postfix();
BufferedReader obj=new BufferedReader(new InputStreamReader(System.in));
System.out.println();
System.out.println("Enter an expression in infix notation");
str=obj.readLine();
System.out.println("Postfix notation is");
in2post.convert(str);
}
}

Program for nth prime number 1<=n<=100000 URGENT
Reshma Subramaniam q1) find next prime number

public static void getprime(int n){
boolean isp = false;
n++;
do{
if(n == 2)
isp = true;
else
{
isp = true;
for(int i = 2; i*i <= n; i++)
{
if(n%i == 0)
{
isp = false;
break;
}
}
}

if(!isp)
n++;
}while(!isp);

output = n;
}
Largest sub array with equal no: of 0s and 1s:
Given the array containing only 0s and 1s, find the length of largest sub array
containing equal number of 0s and 1s.
You need to fill in a function which takes an integer n and an integer array a[]
for(i<=i<n,A[i]=0or1) and sets the output variable to the length of the largest subarray
containing equal no: of 0s and 1s
import java.util.*;
public class HelloWorld{

public static void main(String args[])
{

char[] carray=new char[]{1,0,1,0,0,1};

int i,j,k,diff=0,prevdiff=0;
int n,in=0,out=0;
n=carray.length;

for(i=0;i<n;i++)
{
in=0;
out=0;

for(j=i;j<n;j++)
{
if(carray[j]==0)
in++;
else
out++;
if(in==out)
diff=j-i+1;
if(diff>prevdiff)
prevdiff=diff;
}
}

System.out.println(prevdiff);
}
}
Matrix Chain Multiplication
public class scalar_multiplication
{
// Given an array p[] which represents the chain of matrices such that the ith matrix Ai is of dimension
p[i-1] x p[i].
//We need to write a function MatrixChainOrder() that should return the minimum number of
multiplications needed to multiply the chain.
//
// Input: p[] = {40, 20, 30, 10, 30}
// Output: 26000
// There are 4 matrices of dimensions 40x20, 20x30, 30x10 and 10x30.
// Let the input 4 matrices be A, B, C and D. The minimum number of
// multiplications are obtained by putting parenthesis in following way
// (A(BC))D --> 20*30*10 + 40*20*10 + 40*10*30
// Matrix Ai has dimension p[i-1] x p[i] for i = 1..n

static int MatrixChainOrder(int p[], int i, int j)
{
if (i == j)
{
return 0;
}
int k;
int min = 32767;
int count;

// place parenthesis at different places between first and last matrix,
// recursively calculate count of multiplcations for each parenthesis
// placement and return the minimum count
for (k = i; k < j; k++)
{
count = MatrixChainOrder(p, i, k)
+ MatrixChainOrder(p, k + 1, j)
+ p[i - 1] * p[k] * p[j];

if (count < min)
{
min = count;
}
}

// Return minimum count
return min;
}

// Driver program to test above function
public static void main(String[] args)
{

int arr[] =
{
10, 20, 30, 40, 30
};
int n = arr.length;

System.out.println("Minimum number of multiplications is " + MatrixChainOrder(arr, 1, n - 1));

}
}
LCM of two Numbers
public class LCM {
public static void main(String[] args) {
int a = 36;
int b = 92;
int big;
int small;
// print the two numbers for which the LCM to be calculate
System.out.println("the value of a:" + a);

System.out.println("the value of b:" + b);
{
if (a > b) // check whether a is big or b is big
{
big = a;
small = b;
} else {
big = b;
small = a;
}
for (int i = 1; i <= big; i++) {
if (((big * i) % small) == 0) {
int lcm = big * i; // condition to calculate the LCM of two
// numbers
System.out.println("The least common multiple is " + (lcm));
// print the LCM of two numbers
break;
}
}
}
}
}
import java.util.Scanner;

public class LCM{
public static void main(String[] args){
Scanner aScanner = new Scanner(System.in);

//prompts user for values to find the LCM for, then saves them to m and n
System.out.print("Enter the value of m:");
int m = aScanner.nextInt();
System.out.print("Enter the value of n:");
int n = aScanner.nextInt();
int lcm = (n == m || n == 1) ? m :(m == 1 ? n : 0);
/* this section increases the value of mm until it is greater
/ than or equal to nn, then does it again when the lesser
/ becomes the greater--if they aren't equal. If either value is 1,
/ no need to calculate*/
if (lcm == 0) {
int mm = m, nn = n;
while (mm != nn) {
while (mm < nn) { mm += m; }
while (nn < mm) { nn += n; }
}
lcm = mm;
}
System.out.println("lcm(" + m + ", " + n + ") = " + lcm);
}
}
GCD of two Numbers
public class GCDExample {

public static void main(String args[]){
//Enter two number whose GCD needs to be calculated.
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter first number to find GCD");
int number1 = scanner.nextInt();
System.out.println("Please enter second number to find GCD");
int number2 = scanner.nextInt();

System.out.println("GCD of two numbers " + number1 +" and "
+ number2 +" is :" + findGCD(number1,number2));
private static int findGCD(int number1, int number2) {
//base case
if(number2 == 0){
return number1;
}
return findGCD(number2, number1%number2);
}
}
Output:
Please enter first number to find GCD
54
Please enter second number to find GCD
24
GCD of two numbers 54 and 24 is :6
Code for Jacksparrow
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.*;

public class jack_aparrow
{
// thief has to cross n walls,jumps clu metres,falls down cld metres,walls height array given .find no. of
jumps needed

static int GetJumpCount(int climbUp, int climbDown, int noOfWalls, int wh[])
{
int clu, cld, now;
int n;
int count = 0;

clu = climbUp;
cld = climbDown;
now = noOfWalls;
int jump = 0;
n = wh.length;
for (int i = 0; i < n; i++)
{

int j = clu;
count++; //we set sum to one at every wall because in order to cross //the wall he'd jump at least once
if (j >= wh[i])
{
continue;
} else
{
while (j < wh[i])
{
j = j - cld + clu;
count++;
}
}

}
return count;

}

Find next prime, input 35 output 37

public static void main(String[] abcd) throws java.lang.Exception
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the number of walls");
int walls = Integer.parseInt(br.readLine());
int up = Integer.parseInt(br.readLine());
int down = Integer.parseInt(br.readLine());
int wh[] = new int[walls];
for (int i = 0; i < walls; i++)
{
wh[i] = Integer.parseInt(br.readLine());
}
int op = GetJumpCount(up, down, walls, wh);
System.out.println("no of jumps" + op);
}
}
import java.util.Scanner;

public class NxtPrime {

public static void main(String[] args) {
int i,n,flag=1,count,j,m;
Scanner in=new Scanner(System.in);
System.out.print("enter value of n =");
n= in.nextInt();
m=n+1;
for(i=m;flag!=0;i++)
{
count=0;
for(j=2;j<m;j++)
{
if(i%j==0)
count+=1;
}
if(count==0)
flag=0;

}System.out.print("next prime num is "+(i-1)); // TODO code application logic here
}

}
Code to find the the frequency of lower case alphabets in a string
import java.util.*;

import java.io.*;

public class AlphaC
{
public static void main(String []args)
{
int f[]=new int[26];
for(int i=0;i<26;i++)
{
f[i]=0;
}
char[] charray=new char[]{'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};

System.out.println("enter the string");

Scanner sin=new Scanner(System.in);

String input=sin.nextLine();

for(int m=0;m<input.length();m++)

{
for(int ck=0;ck<26;ck++)

{

if(input.charAt(m)==charray[ck])

{
f[ck]++;
}
}
}
for(int ck=0;ck<26;ck++)
{
if(f[ck]!=0)
System.out.println(charray[ck]+" \t\t "+f[ck]);
}
}}

You might also like