-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEndSemq2.java
More file actions
108 lines (85 loc) · 2.58 KB
/
EndSemq2.java
File metadata and controls
108 lines (85 loc) · 2.58 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
import java.util.*;
public class EndSemq2 {
public static int cost(int A[],int B[],String s1, String s2,int i,int j,int dp[][]){
if(s1.length()==0){
int cost=0;
for(int ind=j;ind>=0;ind--){
cost+=B[ind];
}
return cost;
}
if(s2.length()==0){
int cost=0;
for(int ind=i;ind>=0;ind--){
cost+=A[ind];
}
return cost;
}
if(i<0){
int num=0;
for(int k=j;k>=0;k--){
num=num+B[k];
}
return num;
}
if(j<0){
int num=0;
for(int k=i;k>=0;k--){
num=num+A[k];
}
return num;
}
if(i==0 && j==0){
if(s1.charAt(i)==s2.charAt(j)){
return 0;
}
else{
return A[i]+B[j];
}
}
if(dp[i][j]!=-1) return dp[i][j];
if(s1.charAt(i)==s2.charAt(j)){
dp[i][j]=cost(A, B, s1, s2, i-1, j-1, dp);
}
else{
dp[i][j]=Math.min((A[i]+cost(A, B, s1, s2, i-1, j, dp)), (B[j]+cost(A, B, s1, s2, i, j-1, dp)));
}
return dp[i][j];
}
public static void main(String[] args) {
int Cost=0;
int lengthA, lengthB;
Scanner sc=new Scanner(System.in);
System.out.println("Enter a string");
String s1=sc.next();
lengthA=s1.length();
System.out.println("Enter a string");
String s2=sc.next();
lengthB=s2.length();
System.out.println("Enter costArray1");
int costA[]=new int[lengthA];
for(int i=0;i<lengthA;i++){
costA[i]=sc.nextInt();
}
if(s2=="null"){
Cost=0;
for(int ind=0;ind<s1.length();ind++){
Cost+=costA[ind];
}
}
else{
System.out.println("Enter costArray2");
int costB[]=new int[lengthB];
for(int i=0;i<lengthB;i++){
costB[i]=sc.nextInt();
}
int dp[][]=new int[lengthA][lengthB];
for(int[] row : dp) {
Arrays.fill(row, -1);
}
Cost = cost(costA, costB, s1, s2, lengthA-1, lengthB-1, dp);
System.out.println("Cost is " + Cost);
sc.close();
}
}
}