Knapsack Variation

An investor has saved some money and wants to invest in the stock market. There are a number of stocks to choose from, and they want to buy at most 1 share in any company. The total invested cannot exceed the funds available. A friend who is a stock ma…


This content originally appeared on DEV Community and was authored by Santhosh Balasa

An investor has saved some money and wants to invest in the stock market. There are a number of stocks to choose from, and they want to buy at most 1 share in any company. The total invested cannot exceed the funds available. A friend who is a stock market expert has predicted the value of each stock after 1 year. Determine the maximum profit that can be earned at the end of the year assuming the predictions come true.

saving = 250
current_value = [175, 133, 109, 201, 97]
future_value = [200, 125, 128, 228, 133]

# This is a 0/1 knapsack based algorithm
t = [[-1 for i in range(1000)] for j in range(saving)] # n x W matrix
def knapsack(w, v, W, n):
    if n == 0 or W == 0:
        return 0
    if t[n][W] != -1:
        return t[n][W]
    if w[n-1] <= W:
        t[n][W] = max(
            v[n-1] + knapsack(w, v, W-w[n-1], n-1),
            knapsack(w, v, W, n-1)
        )
    else:
        t[n][W] = knapsack(w, v, W, n-1)
    return t[n][W]

profits = [0 if j<j else j-i for i, j in zip(current_value, future_value)]
print(knapsack(current_value, profits, saving, len(current_value)))


This content originally appeared on DEV Community and was authored by Santhosh Balasa


Print Share Comment Cite Upload Translate Updates
APA

Santhosh Balasa | Sciencx (2021-06-01T11:08:23+00:00) Knapsack Variation. Retrieved from https://www.scien.cx/2021/06/01/knapsack-variation/

MLA
" » Knapsack Variation." Santhosh Balasa | Sciencx - Tuesday June 1, 2021, https://www.scien.cx/2021/06/01/knapsack-variation/
HARVARD
Santhosh Balasa | Sciencx Tuesday June 1, 2021 » Knapsack Variation., viewed ,<https://www.scien.cx/2021/06/01/knapsack-variation/>
VANCOUVER
Santhosh Balasa | Sciencx - » Knapsack Variation. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2021/06/01/knapsack-variation/
CHICAGO
" » Knapsack Variation." Santhosh Balasa | Sciencx - Accessed . https://www.scien.cx/2021/06/01/knapsack-variation/
IEEE
" » Knapsack Variation." Santhosh Balasa | Sciencx [Online]. Available: https://www.scien.cx/2021/06/01/knapsack-variation/. [Accessed: ]
rf:citation
» Knapsack Variation | Santhosh Balasa | Sciencx | https://www.scien.cx/2021/06/01/knapsack-variation/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.