Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
PHP 7 Data Structures and Algorithms

You're reading from   PHP 7 Data Structures and Algorithms Implement linked lists, stacks, and queues using PHP

Arrow left icon
Product type Paperback
Published in May 2017
Publisher Packt
ISBN-13 9781786463890
Length 340 pages
Edition 1st Edition
Languages
Arrow right icon
Author (1):
Arrow left icon
Mizanur Rahman Mizanur Rahman
Author Profile Icon Mizanur Rahman
Mizanur Rahman
Arrow right icon
View More author details
Toc

Table of Contents (14) Chapters Close

Preface 1. Introduction to Data Structures and Algorithms FREE CHAPTER 2. Understanding PHP Arrays 3. Using Linked Lists 4. Constructing Stacks and Queues 5. Applying Recursive Algorithms - Recursion 6. Understanding and Implementing Trees 7. Using Sorting Algorithms 8. Exploring Search Options 9. Putting Graphs into Action 10. Understanding and Using Heaps 11. Solving Problems with Advanced Techniques 12. PHP Built-In Support for Data Structures and Algorithms 13. Functional Data Structures with PHP

0 - 1 knapsack

A knapsack is a bag with straps, usually carried by soldiers to help them take their necessary items or valuables during their journey. Each item has a value and definite weight attached to it. So, the soldier has to pick the most valuable items within their maximum weight limit as they cannot put everything in their bag. The word 0/1 means that either we can take it or leave it. We cannot take an item partially. This is known as the famous 0-1 knapsack problem. We will take the bottom-up approach for solving the 0-1 knapsack problem. Here is the pseudocode for the solution:

Procedure knapsack(n, W, w1,...,wN, v1,...,vN) 
for w = 0 to W
M[0, w] = 0

for i = 1 to n
for w = 0 to W

if wi > w :
M[i, w] = M[i-1, w]
else :
M[i, w] = max (M[i-1, w], vi + M[i-1, w-wi ])
return M[n, W]

end procedure

For example, if we have five items, ...

lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €18.99/month. Cancel anytime