Expand file tree Collapse file tree 4 files changed +21
-16
lines changed Original file line number Diff line number Diff line change @@ -183,8 +183,12 @@ include::chapters/greedy-algorithms--knapsack-problem.adoc[]
183
183
184
184
= Divide and Conquer Algorithms
185
185
186
+ include::chapters/divide-and-conquer--intro.adoc[]
187
+
188
+
186
189
:leveloffset: +1
187
190
191
+
188
192
:leveloffset: -1
189
193
190
194
= Backtracking Algorithms
Original file line number Diff line number Diff line change @@ -48,3 +48,7 @@ Let's implement this algorithm!
48
48
----
49
49
include::{codedir}/algorithms/knapsack-fractional.js[tag=snippet,indent=0]
50
50
----
51
+
52
+ What's the runtime of this algorithm?
53
+
54
+ We have to sort the array based on value/weight ratio. Sorting runtime is O(n log n). The rest is linear operations, so we the answer is _O(n log n)_ for our greedy algorithm.
Original file line number Diff line number Diff line change @@ -75,6 +75,10 @@ BigInt allows to operate beyond the maximum safe limit of integers (Number.MAX_S
75
75
- <<Adaptive>>: [big]#✅# Yes
76
76
- Time Complexity: [big]#⛔️# <<Quadratic>> _O(n^2^)_
77
77
78
+ .How to explain dynamic programming to kids? 👶
79
+ ----
80
+ test [big]*🤯*
81
+ ----
78
82
79
83
== Images
80
84
Original file line number Diff line number Diff line change 1
1
// tag::snippet[]
2
2
/**
3
- *
3
+ * Solves Bounded Knapsack Problem (BKP)
4
+ * You can take fractions or whole part of items.
4
5
* @param {Array } input array of objects with the shape {value, weight}
5
6
* @param {Number } max maximum weight for knapsack
6
7
*/
@@ -16,25 +17,17 @@ function solveFractionalKnapsack(input, max) {
16
17
const bestRatioItem = input . pop ( ) ;
17
18
18
19
if ( weight + bestRatioItem . weight <= max ) {
19
- // take item as a whole
20
- bestRatioItem . proportion = 1 ;
21
- items . push ( bestRatioItem ) ;
22
- weight += bestRatioItem . weight ;
23
- value += bestRatioItem . value ;
24
- } else {
25
- // take a fraction of the item
20
+ bestRatioItem . proportion = 1 ; // take item as a whole
21
+ } else { // take a fraction of the item
26
22
bestRatioItem . proportion = ( max - weight ) / bestRatioItem . weight ;
27
- items . push ( bestRatioItem ) ;
28
- weight += bestRatioItem . proportion * bestRatioItem . weight ;
29
- value += bestRatioItem . proportion * bestRatioItem . value ;
30
23
}
24
+
25
+ items . push ( bestRatioItem ) ;
26
+ weight += bestRatioItem . proportion * bestRatioItem . weight ;
27
+ value += bestRatioItem . proportion * bestRatioItem . value ;
31
28
}
32
29
33
- return {
34
- weight,
35
- value,
36
- items,
37
- } ;
30
+ return { weight, value, items } ;
38
31
}
39
32
// end::snippet[]
40
33
0 commit comments