Go to en.wikipedia.org/wiki/Knapsack_problem, and read the section on Greedy Approximation Algorithm, because that’s what your code is doing.
The problem requires an exact solution, not an approximation, so look elsewhere on that page for a better approach.