Skip to content

Commit 815f8b0

Browse files
authored
Update Q-01: 0-1 KnapSack Problem.java
1 parent 865bb5d commit 815f8b0

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed

DP KnapSack Pattern || DP Subsequence Pattern/Q-01: 0-1 KnapSack Problem.java

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -114,6 +114,28 @@ public static int solvetab(int w,int wt[],int val[],int n){
114114
}
115115
return tab[n][w];
116116
}
117+
//Space Optimize.
118+
// TC : O(n*w)
119+
// SC : 2*O(w)
120+
public static int solveOpt(int W,int[] wt, int[] val,int n){
121+
122+
int[] curr = new int[W+1];
123+
int[] prev = new int[W+1];
124+
125+
for(int i=1;i<n+1;i++){
126+
for(int j=1;j<W+1;j++){
127+
if(wt[i-1]>j){
128+
curr[j] =prev[j];
129+
}else{
130+
curr[j] = Math.max(prev[j-wt[i-1]]+val[i-1] , prev[j]);
131+
}
132+
}
133+
for(int k=0;k<W+1;k++){
134+
prev[k] = curr[k];
135+
}
136+
}
137+
return curr[W];
138+
}
117139

118140
}
119141

0 commit comments

Comments
 (0)