You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
System.out.println("Fibonacci of 5: " + fibonacci(5)); // Output: 5
122
+
System.out.println("Fibonacci of 10: " + fibonacci(10)); // Output: 55
123
+
}
124
+
}
125
+
```
126
+
</TabItem>
127
+
128
+
<TabItemvalue="JavaScript"label="JavaScript">
129
+
```jsx showLineNumbers
130
+
functionfibonacci(n) {
131
+
if (n <=1) return n;
132
+
133
+
let a =0, b =1, c;
134
+
for (let i =2; i <= n; i++) {
135
+
c = a + b;
136
+
a = b;
137
+
b = c;
138
+
}
139
+
return b;
140
+
}
141
+
142
+
// Test the function
143
+
console.log("Fibonacci of 5:", fibonacci(5)); // Output: 5
144
+
console.log("Fibonacci of 10:", fibonacci(10)); // Output: 55
145
+
```
146
+
</TabItem>
81
147
82
-
return fib(n)
83
148
84
-
# Test the function
85
-
print(fibonacci(5)) # Output: 5
86
-
print(fibonacci(10)) # Output: 55
87
-
```
149
+
</Tabs>
88
150
89
151
In this example, we use dynamic programming to efficiently compute Fibonacci numbers. We create a memoization table to store the computed values and avoid redundant computations. The recursive function `fib` checks if the value is already computed in the memoization table before computing it. This approach significantly improves the efficiency of the algorithm.
items.sort((a, b) => (b.value/b.weight) - (a.value/a.weight));
222
+
223
+
let totalValue =0;
224
+
let totalWeight =0;
225
+
226
+
for (let item of items) {
227
+
if (totalWeight +item.weight<= capacity) {
228
+
totalValue +=item.value;
229
+
totalWeight +=item.weight;
230
+
}
231
+
}
232
+
233
+
return totalValue;
234
+
}
235
+
236
+
// Example usage
237
+
let values = [60, 100, 120];
238
+
let weights = [10, 20, 30];
239
+
let capacity =50;
240
+
241
+
let maxValue =knapsackGreedy(values, weights, capacity);
242
+
console.log("Maximum value:", maxValue);
243
+
244
+
245
+
```
246
+
</TabItem>
247
+
248
+
249
+
</Tabs>
97
250
98
251
This code demonstrates the Greedy algorithm in action by solving the Knapsack problem. The goal is to maximize the total value of items that can be put into a knapsack with a given capacity. The algorithm selects items based on their value-to-weight ratio, choosing the most valuable items first until the knapsack is full.
0 commit comments