Problem:


Score : 100 points

Problem Statement

There are N items, numbered 1, 2, \ldots, N.
For each i (1 \leq i \leq N), Item i has a weight of w_i and a value of v_i.

Taro has decided to choose some of the N items and carry them home in a knapsack.
The capacity of the knapsack is W, which means that the sum of the weights of items taken must be at most W.

Find the maximum possible sum of the values of items that Taro takes home.

Constraints

All values in input are integers.

1 \leq N \leq 100

1 \leq W \leq 10^5

1 \leq w_i \leq W

1 \leq v_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N W
w_1 v_1
w_2 v_2
:
w_N v_N

Output

Print the maximum possible sum of the values of items that Taro takes home.

Sample Input 1

3 8
3 30
4 50
5 60

Sample Output 1

90

Items 1 and 3 should be taken.
Then, the sum of the weights is 3 + 5 = 8, and the sum of the values is 30 + 60 = 90.

Sample Input 2

5 5
1 1000000000
1 1000000000
1 1000000000
1 1000000000
1 1000000000

Sample Output 2

5000000000

The answer may not fit into a 32-bit integer type.

Sample Input 3

6 15
6 5
5 6
6 4
6 6
3 5
7 2

Sample Output 3

17

Items 2, 4 and 5 should be taken.
Then, the sum of the weights is 5 + 6 + 3 = 14, and the sum of the values is 6 + 6 + 5 = 17.



Sample input:
3 8
3 30
4 50
5 60


Sample output:
90

Submission status: Time Limit Exceeded

Solution code:
def knapsack(weight,profit,capacities):
    
    n = len(weight)
    dp = [[-1 for _ in range(capacities+1)] for _ in range(n+1)]
    
    
    for no in range(n+1):
        for capacity in range(capacities+1):
            
            if no == 0 or capacity == 0:
                dp[no][capacity] =  0
    
    
            elif weight[no-1] <= capacity:
                 dp[no][capacity] = max(profit[no-1] + dp[no-1][capacity-weight[no-1]],
                                        dp[no-1][capacity])
            else: #weight[no-1] > capacity:
                dp[no][capacity] = dp[no-1][capacity]
        
    return dp[no][capacity]
    
n,W = map(int,input().split())
w,v = [],[]
for _ in range(n):
    x,y = map(int,input().split())
    w.append(x)
    v.append(y)
    #n -= 1
print(knapsack(w,v,W))

Submission status: Time Limit Exceeded

Solution code:
def knapsack(weight,profit,capacity,no):
    if no == 0 or capacity == 0:
        return 0
    
    if weight[no-1] <= capacity:
        return max(profit[no-1] + knapsack(weight,profit,capacity-weight[no-1],no-1),
                   knapsack(weight,profit,capacity,no-1))
    if weight[no-1] > capacity:
        return knapsack(weight,profit,capacity,no-1)
    
n,W = map(int,input().split())
w,v = [],[]
for _ in range(n):
    x,y = map(int,input().split())
    w.append(x)
    v.append(y)
    #n -= 1
print(knapsack(w,v,W,n))

Submission status: Time Limit Exceeded

Solution code:
def dp(W,wt,val,n):
    K = [[0 for x in range(W + 1)] for x in range(n + 1)] 
    for i in range(n + 1): 
        for w in range(W + 1): 
            if i == 0 or w == 0: 
                K[i][w] = 0
            elif wt[i-1] <= w: 
                K[i][w] = max(val[i-1] + K[i-1][w-wt[i-1]],  K[i-1][w]) 
            else: 
                K[i][w] = K[i-1][w] 
  
    return K[n][W]

n,w = list(map(int,input().split()))
val = []
wt = []
for _ in range(n):
    p,q = list(map(int,input().split()))
    wt.append(p)
    val.append(q)

print(dp(w,wt,val,n))

Submission status: Time Limit Exceeded

Solution code:
def dp(w,wt,val,n):
    if n==0 or w==0:
        return 0
    
    if wt[n-1]>w:
        return dp(w,wt,val,n-1)
    
    else:
        return max(val[n-1]+dp(w-wt[n-1],wt,val,n-1),dp(w,wt,val,n-1))

n,w = list(map(int,input().split()))
val = []
wt = []
for _ in range(n):
    p,q = list(map(int,input().split()))
    wt.append(p)
    val.append(q)

print(dp(w,wt,val,n))

Submission status: Time Limit Exceeded

Solution code:
n,c = list(map(int, input().split()))
W=[]
P=[]
for _ in range(n):
    w,val = list(map(int, input().split()))
    W.append(w)
    P.append(val)
dp=[]
for i in range(n+1):
    dp.append([0]*(c+1))
for i in range(1,n+1):
    for j in range(1,c+1):
        inc=0
        exc=0
        if j-W[i-1]>=0:
            inc=P[i-1]+dp[i-1][j-W[i-1]]
        exc=dp[i-1][j]
        dp[i][j]=max(inc,exc)
print(dp[n][c])

Submission status: Time Limit Exceeded

Solution code:
n,w=map(int,input().split())
l=[list(map(int,input().split())) for i in range(n)]
dp=[[0 for j in range(w+1)] for i in range(n+1)]
for i in range(n):
  for j in range(w+1):
    if l[i][0]<=j:
      dp[i+1][j]=max(dp[i][j],dp[i][j-l[i][0]]+l[i][1])
    else:
      dp[i+1][j]=dp[i][j]
print(dp[n][w])

Submission status: Time Limit Exceeded

Solution code:
import numpy as np



N,W = map(int,input().split())
items = [[int(a) for a in input().split()]]
for i in range(N-1):
    items.append([int(a) for a in input().split()])
items = np.array(items)
dp = np.full((N+1,W+1),0,dtype=np.int64)
dp[0][W] = 0
for i in range(N):
    for w in range(W+1):
        if w-items[i][0] >= 0:
            dp[i+1][w] =max(dp[i][w],dp[i][w-items[i][0]]+items[i][1])
        else:
            dp[i+1][w] = dp[i][w]
print(dp[N][W])

Submission status: Time Limit Exceeded

Solution code:
N, W = map(int, input().split())
kpsk_list = [list(map(int, input().split())) for _ in range(N)]
#print(kpsk_list)
dp = [[0]*(W+1) for _ in range(N+1)]
#print(dp)
for n in range(1, N+1): #何個目までのアイテムを考慮するか
  for w in range(W+1): #各重さでの価値の最大値を求める.
    #print(f"n:{n},w:{w}")
    if w - kpsk_list[n-1][0] < 0: 
      dp[n][w] = dp[n-1][w]
    else:
      dp[n][w] = max(dp[n-1][w], dp[n-1][w - kpsk_list[n-1][0]] + kpsk_list[n-1][1])
    #print(dp)

print(dp[N][W])
  # dp[n]について各重さsum_w(=0~W)の時の最大価値をdpテーブルに保存していく.

Submission status: Time Limit Exceeded

Solution code:
N,W = map(int,input().split())
w=[]
v=[]
dp = {}
for i in range(N):
  x,y = map(int,input().split())
  w.append(x)
  v.append(y)
ans = [0]
def knap(index,W,temp):
    #base case
    if (index,W) in dp:
        return dp[(index,W)]
    if index == len(w):
        return 0
    if W - w[index] >= 0:
        dp[(index,W)] = max(v[index]+knap(index + 1,W-w[index],temp+v[index]) , knap(index+1 , W,temp))
        return dp[(index,W)]
    else:
        dp[(index,W)] = knap(index+1,W,temp)
        return dp[(index,W)]
print(knap(0,W,0))

Submission status: Time Limit Exceeded

Solution code:
N,W = map(int,input().split())
w=[]
v=[]
for i in range(N):
  x,y = map(int,input().split())
  w.append(x)
  v.append(y)
ans = [0]
def knap(index,W,temp):
	#base case 
    if index == len(w):
        ans[0] = max(ans[0],temp)
        return 0
    if W - w[index] >= 0:
        return max(v[index]+knap(index + 1,W-w[index],temp+v[index]) , knap(index+1 , W,temp))
    else:
        return knap(index+1,W,temp)
knap(0,W,0)
print(ans[0])

Submission status: Time Limit Exceeded

Solution code:
# 常備セット
import numpy as np
import scipy.sparse as sps
import scipy.misc as spm
import collections as col
import functools as func
import itertools as ite
import fractions as frac
import math as ma
import copy as cp
import sys
def sinput(): return sys.stdin.readline()
def iinput(): return int(sinput())
def imap(): return map(int, sinput().split())
def fmap(): return map(float, sinput().split())
def iarr(): return list(imap())
def farr(): return list(fmap())
def sarr(): return sinput().split()
sys.setrecursionlimit(10**7)
MOD = 10**9 + 7; EPS = sys.float_info.epsilon
PI = np.pi; EXP = np.e; INF = np.inf

n,wmax = imap()
wv = np.array([iarr() for i in range(n)])
w,v = wv.T[0], wv.T[1]
#dp = np.zeros((n+1, wmax+1),dtype=np.int64)
dp = [[0 for ww in range(wmax+1)] for i in range(n+1)]

for i in range(n):
    for ww in range(wmax+1):
        dp[i+1][ww] = max(dp[i][ww], dp[i][ww-w[i]]+v[i]) if ww-w[i]>=0 else dp[i][ww]

ans = dp[n][wmax]
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
def input(): return sys.stdin.readline().rstrip()
def main():
    n,weight=map(int,input().split())
    WV=[tuple(map(int,input().split())) for i in range(n)]
    dp=[[0]*(weight+1) for _ in range(n+1)] #品物iまでについて，ナップサックの重さの総和がjのときの価値の総和
    for i in range(n):
        ni=i+1
        w,v=WV[ni-1]
        for j in range(weight+1):
            dp[ni][j]=max(dp[ni][j],dp[i][j])
            if j+w<=weight and (j==0 or dp[i][j]>0):
                dp[ni][j+w]=max(dp[ni][j+w],dp[i][j]+v)
    print(max(dp[n]))
            



if __name__=='__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
# 常備セット
import numpy as np
import scipy.sparse as sps
import scipy.misc as spm
import collections as col
import functools as func
import itertools as ite
import fractions as frac
import math as ma
import copy as cp
import sys
def sinput(): return sys.stdin.readline()
def iinput(): return int(sinput())
def imap(): return map(int, sinput().split())
def fmap(): return map(float, sinput().split())
def iarr(): return list(imap())
def farr(): return list(fmap())
def sarr(): return sinput().split()
sys.setrecursionlimit(10**7)
MOD = 10**9 + 7; EPS = sys.float_info.epsilon
PI = np.pi; EXP = np.e; INF = np.inf

n,wmax = imap()
wv = np.array([iarr() for i in range(n)])
w,v = wv.T[0], wv.T[1]
dp = np.zeros((n+1, wmax+1),dtype=np.int64)

for i in range(n):
    for ww in range(wmax+1):
        dp[i+1][ww] = max(dp[i][ww], dp[i][ww-w[i]]+v[i]) if ww-w[i]>=0 else dp[i][ww]

ans = dp[n][wmax]
print(ans)

Submission status: Time Limit Exceeded

Solution code:
N,W=map(int,input().split(' '))
bag=[tuple(map(int,input().split(' '))) for _ in range(N)]
dp1,dp2=[0]*(W+1),[0]*(W+1)
for i in range(N):
    dp1=dp2
    dp2=[0]*(W+1)
    for j in range(1,W+1):
        if j<bag[i][0]:
            dp2[j]=dp1[j]
        else:
            dp2[j]=max(dp1[j],dp1[j-bag[i][0]]+bag[i][1])
print(dp2[-1])

Submission status: Time Limit Exceeded

Solution code:
import collections,sys
def LI(): return list(map(int,sys.stdin.readline().rstrip().split()))
N,W = LI()
wv = [LI() for _ in range(N)]
dp = [collections.defaultdict(int) for _ in range(N+1)] #1_indexed
dp[0][0] = 0
for i in range(1,N+1):
    w,v = wv[i-1]
    for dw,dv in dp[i-1].items():
        dp[i][dw] = max(dp[i][dw],dv)
        if dw+w<=W:
            dp[i][dw+w] = max(dp[i][dw+w],dv+v)
print(max(dp[-1].values()))

Submission status: Time Limit Exceeded

Solution code:
N,W=map(int,input().split())
w=[0]*(N+1)
v=[0]*(N+1)
for i in range(1,N+1):
  w[i],v[i]=map(int,input().split())

dp=[[0 for _ in range(W+1)] for _ in range(N+1)]

for i in range(1,N+1):
  for j in range(1,W+1):
    #print("i=",i,"j=",j)
    #dp[i][j]=max(dp[i][j],dp[i-1][j])
    #if j-w[i]<0: continue
    #dp[i][j]=max(dp[i][j],dp[i-1][j-w[i]]+v[i])
    if j-w[i]<0:
      dp[i][j]=max(dp[i][j],dp[i-1][j])
    else:
      dp[i][j]=max(dp[i][j],dp[i-1][j],dp[i-1][j-w[i]]+v[i])

#print(dp)
print(dp[N][W])

Submission status: Time Limit Exceeded

Solution code:
N,W=map(int,input().split())
w=[0]*(N+1)
v=[0]*(N+1)
for i in range(1,N+1):
  w[i],v[i]=map(int,input().split())

dp=[[0 for _ in range(W+1)] for _ in range(N+1)]

for i in range(1,N+1):
  for j in range(1,W+1):
    #print("i=",i,"j=",j)
    dp[i][j]=max(dp[i][j],dp[i-1][j])
    if j-w[i]<0: continue
    dp[i][j]=max(dp[i][j],dp[i-1][j-w[i]]+v[i])

#print(dp)
print(dp[N][W])

Submission status: Time Limit Exceeded

Solution code:
n,wt=map(int,input().split())
v=[0]*n
w=[0]*n
for i in range(n):
    a,b=map(int,input().split())
    w[i]=a
    v[i]=b
k=[[0 for j in range(wt+1)] for i in range(n+1)]
for i in range(n+1):
    for j in range(wt+1):

        if(n==0 or wt==0):
            k[i][j]=0
        
        if(w[i-1]<=j):
            k[i][j]=max(k[i-1][j-w[i-1]]+v[i-1],k[i-1][j])
        else:
            k[i][j]=k[i-1][j]
             
print(k[n][wt])

Submission status: Time Limit Exceeded

Solution code:
N,W = map(int,input().split())
Value = []
weight = []
inf=float("inf")
dp=[[-inf for i in range(W+1)] for j in range(N+1)]
for i in range(W+1): dp[0][i]=0

for i in range(N):
    w,v = map(int,input().split())
    Value.append(v)
    weight.append(w)


for i in range(N):
  for w in range(W+1):
    if w>=weight[i]:
      dp[i+1][w] = max(dp[i][w-weight[i]]+Value[i],dp[i][w])
    else:
      dp[i+1][w] = dp[i][w]

print(dp[N][W])

Submission status: Time Limit Exceeded

Solution code:

l=list(map(int,input().split()))
n=l[0]
w=l[1]
va=[0]*n
wa=[0]*n
for i in range(n):
        
    x=list(map(int,input().split()))
    wa[i]=x[0]
    va[i]=x[1]
dp=[[0 for i in range(w+1)] for j in range(n+1)]
for i in range(1,n+1):
  for j in range(1,w+1):
    if wa[i-1]>j:
      dp[i][j]=dp[i-1][j]
    else:
      dp[i][j]=max(dp[i-1][j],dp[i-1][j-wa[i-1]]+va[i-1])
print(dp[-1][-1])

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
n,w_max=map(int,input().split())
w_list=[0]
w_list=np.array(w_list)
v_list=[0]
v_list=np.array(v_list)
for i in range(n):
  w,v=map(int,input().split())
  w_tmp=w_list+w
  v_tmp=v_list+v
  w_list=np.concatenate([w_list, w_tmp[np.where(w_tmp<=w_max)]])
  v_list=np.concatenate([v_list, v_tmp[np.where(w_tmp<=w_max)]])
index=np.where(w_list<=w_max)[0]
max_value=0
for i in range(len(index)):
  max_value=max(v_list[index[i]],max_value)

#print(np.where(w_list<=w)[0])
#print(np.where(w_list<=w_max))
#print(w_list)
print(max_value)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
n,w_max=map(int,input().split())
w_list=[0]
w_list=np.array(w_list)
v_list=[0]
v_list=np.array(v_list)
for i in range(n):
  w,v=map(int,input().split())
  w_tmp=w_list+w
  v_tmp=v_list+v
  w_list=np.concatenate([w_list, w_tmp])
  v_list=np.concatenate([v_list, v_tmp])
index=np.where(w_list<=w_max)[0]
max_value=0
for i in range(len(index)):
  max_value=max(v_list[index[i]],max_value)

#print(np.where(w_list<=w)[0])
#print(np.where(w_list<=w_max))
#print(w_list)
print(max_value)

Submission status: Time Limit Exceeded

Solution code:
n,wt=map(int,input().split())
v=[0]*n
w=[0]*n
for i in range(n):
    a,b=map(int,input().split())
    w[i]=a
    v[i]=b
def knp(wt,v,w,n):
    if(n==0 or wt==0):
        return 0
    
    if(w[n-1]>wt):
        return knp(wt,v,w,n-1)
    else:
        return max(v[n-1]+knp(wt-w[n-1],v,w,n-1),knp(wt,v,w,n-1)) 
print(knp(wt,v,w,n))

Submission status: Time Limit Exceeded

Solution code:
import sys
from collections import Counter
from collections import deque
def input(): return sys.stdin.readline().strip()
def mp(): return map(int,input().split())
def lmp(): return list(map(int,input().split()))

n,w=mp()
item=[lmp() for i in range(n)]
dp=[[0]*(w+1) for i in range(n+1)]
for i in range(n):
    for k in range(1,w+1):
        if k<item[i][0]:
            dp[i+1][k]=dp[i][k]
        else:
            dp[i+1][k]=max(dp[i][k],dp[i][k-item[i][0]]+item[i][1])
print(dp[-1][-1])

Submission status: Time Limit Exceeded

Solution code:
n,w = map(int,input().split())
mp = [list(map(int,input().split())) for i in range(n)]

dp = [[0]*(w+1) for i in range(n+1)]
for i in range(1,n+1):
    for j in range(w+1):
        nx = j-mp[i-1][0]
        dp[i][j] = dp[i-1][j]
        if(nx < 0):
            continue
        dp[i][j] = max(dp[i-1][j],dp[i-1][j-mp[i-1][0]]+mp[i-1][1])
        
print(dp[-1][-1])

Submission status: Time Limit Exceeded

Solution code:
n,w = map(int,input().split())
mp = [list(map(int,input().split())) for i in range(n)]

dp = [[0]*(w+1) for i in range(n+1)]
for i in range(1,n+1):
    for j in range(w+1):
        nx = j-mp[i-1][0]
        dp[i][j] = dp[i-1][j]
        if(nx < 0):
            continue
        dp[i][j] = max(dp[i-1][j],dp[i-1][j-mp[i-1][0]]+mp[i-1][1])
        
print(max(dp[-1]))

Submission status: Time Limit Exceeded

Solution code:
n,m=map(int,input().split())
dp = [[0]*(m+1) for i in range(n+1)]
for i in range(1,n+1):
  w,v=map(int,input().split())
  for j in range(m+1):
    if j < w:
      dp[i][j] = dp[i-1][j]
    else:
      dp[i][j] = max(dp[i-1][j-w]+v,dp[i-1][j])
print(dp[n][m])

Submission status: Time Limit Exceeded

Solution code:
# coding: utf-8
# Your code here!


N, W = map(int, input().split())

dp = [[0]*(W+1) for _ in range(N+1)]

for i in range(1, N+1):
    w, v = map(int, input().split())
    for j in range(W+1):
        if j-w >= 0:
            dp[i][j] = max(dp[i-1][j-w]+v, dp[i][j])
        dp[i][j] = max(dp[i-1][j], dp[i][j])

# print(dp)
print(dp[N][W])

Submission status: Time Limit Exceeded

Solution code:
# N, W = 3, 8
# ARR = [
#     [3, 30],
#     [4, 50],
#     [5, 60],
# ]
#
N, W, = 6, 15
ARR = [
    [6, 5],
    [5, 6],
    [6, 4],
    [6, 6],
    [3, 5],
    [7, 2],
]


N,W = map(int,input().split())
ARR = []

for i in range(N):
    ARR.append(list(map(int,input().split())))


def calculate(n, w, arr):
    srr = [[0] * (w + 1) for i in range (n + 1)]

    for i in range(1, n + 1):
        for j in range(1, w + 1):
            if (j - arr[i-1][0]) >= 0:
                s1 = srr[i-1][j - arr[i-1][0]] + arr[i-1][1]
                s2 = srr[i-1][j]
                srr[i][j] = max(s1, s2)
            else:
                srr[i][j] = srr[i - 1][j]

    print(srr[-1][-1])


calculate(N, W, ARR)

Submission status: Time Limit Exceeded

Solution code:
def main():
    n, w_max = map(int, input().split())
    dp = [[0] * (w_max + 1) for _ in range(n + 1)]
    items = [tuple(map(int, input().split())) for _ in range(n)]
    for i1 in range(1, n + 1):
        w, v = items[i1 - 1][0], items[i1 - 1][1]
        for col in range(1, w_max + 1):
            if w <= col:
                dp[i1][col] = max(dp[i1 - 1][col], dp[i1 - 1][col - w] + v)
            else:
                dp[i1][col] = dp[i1 - 1][col]

    print(dp[-1][-1])


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
def main():
    n, w_max = map(int, input().split())
    dp = [[0] * (w_max + 1) for _ in range(n + 1)]
    for i1 in range(1, n + 1):
        w, v = map(int, input().split())
        for col in range(1, w_max + 1):
            if w <= col:
                dp[i1][col] = max(dp[i1 - 1][col], dp[i1 - 1][col - w] + v)
            else:
                dp[i1][col] = dp[i1 - 1][col]

    print(dp[-1][-1])


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
n, W = map(int, input().split())

# dp[i] - the maximum total value of items with total weight EXACTLY i
dp = [0]*(W+1)

for _ in range(n):
    w, v = map(int, input().split())
    
    # reverse order is important for 0/1. if we go dp[0] --> dp[3] --> dp[6], than item with weight 3 will get 
    # repeated twice for dp[6], but reverse we will only encounter each item once for each dp[i]

    for cap in range(W-w, -1, -1): 
        dp[cap+w] = max(dp[cap+w], dp[cap] + v)
    
# the maximum total value of items with total weight EXACTLY i
ans = 0
for i in range(W+1):
    ans = max(ans, dp[i])
print(ans)

Submission status: Time Limit Exceeded

Solution code:
def iterative_knapsack(W, N):
    memo = [[0]*(n+1) for _ in range(W + 1)]

    for i in range(1, N+1):
        for capacity in range(1, W+1):
            if weights[i-1] > capacity:
                memo[capacity][i] = memo[capacity][i-1]
            else:
                exclude = memo[capacity][i-1]
                include = values[i-1] + memo[capacity-weights[i-1]][i-1]
                memo[capacity][i] = max(include, exclude)

    return memo[W][N]

n, W = map(int, input().split())
weights = []
values = []

for _ in range(n):
    w, v = map(int, input().split())
    weights.append(w)
    values.append(v)

# memo[w][n] - max value we can obtain with capacity w and number of items n

print(iterative_knapsack(W, n))

Submission status: Time Limit Exceeded

Solution code:
def memo_knapsack(w, n):
    if memo[w][n]!=-1:
        return memo[w][n]
    else:
        if w == 0 or n == 0: return 0 # no capacity knapsack has 0 value; no items has 0 value

        if weights[n-1]>w:
            # cant include
            memo[w][n] = memo_knapsack(w, n-1)
            return memo[w][n]

        else:
            include = values[n-1] + memo_knapsack(w - weights[n-1], n-1)
            exclude = memo_knapsack(w, n-1)

            memo[w][n] = max(include, exclude)
            return memo[w][n]

n, W = map(int, input().split())
weights = []
values = []

for _ in range(n):
    w, v = map(int, input().split())
    weights.append(w)
    values.append(v)

# memo[w][n] - max value we can obtain with capacity w and number of items n
memo = [[-1]*(n+1) for _ in range(W + 1)]

print(memo_knapsack(W, n))

Submission status: Time Limit Exceeded

Solution code:
N,W = map(int,input().split())
wv = [list(map(int,input().split())) for _ in range(N)]
dp = [[0]*(W+1) for _ in range(N+1)]
 
for i in range(N):
  for j in range(W+1):
    if j - wv[i][0] >= 0:
      dp[i+1][j] = max(dp[i+1][j], dp[i][j-wv[i][0]] + wv[i][1])
    dp[i+1][j] = max(dp[i+1][j], dp[i][j])
 
ans = 0
 
print(dp[N][W])

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
n, w = map(int, input().split())
items = [list(map(int, input().split())) for _ in range(n)]
items = np.array(items)
# dp[n-1][w] solution
# dp[i][w] = max(dp[i-1][w-items[0][0]]+items[0][1], dp[i-1][w])
dp = np.zeros((n,w+1), dtype='int64')
if items[0][0] <= w:
    dp[0, items[0][0]:] = items[0][1]
for i in range(1,n):
    for j in range(0,w+1):
        if j-items[i][0] >= 0:
            dp[i][j] = max(dp[i-1][j-items[i][0]]+items[i][1], dp[i-1][j])
        else:
            dp[i][j] = dp[i-1][j]
print(dp[n-1][w])

Submission status: Time Limit Exceeded

Solution code:
import numpy as np

n, w = list(map(int, input().split()))
wv = np.array([list(map(int, input().split())) for i in range(n)])

dp = np.zeros((w + 1, n), dtype=np.int)
dp[wv[0, 0]:, 0] = np.full(dp[wv[0, 0]:, 0].shape, wv[0, 1])
for i in range(1, n):
    dp[:, i] = dp[:, i - 1]
    wNew, vNew = wv[i, 0], wv[i, 1]
    dp[wNew:, :] = np.fmax(dp[wNew:, :], vNew + dp[:-wNew, :])

print(dp[w, n - 1])

Submission status: Time Limit Exceeded

Solution code:
N, W = map(int, input().strip().split())

values = []
weights = []

for _ in range(N):
    w, v = map(int, input().strip().split())
    weights.append(w)
    values.append(v)
    
dp = [0]*(W+1)
for i in range(N):
    curr_v = values[i]
    curr_w = weights[i]
    for w in range(W, weights[i] - 1, -1):
        dp[w] = max(dp[w], curr_v + dp[w - curr_w])

print(dp[W])

Submission status: Time Limit Exceeded

Solution code:
N, W = map(int, input().strip().split())

values = []
weights = []

for _ in range(N):
    w, v = map(int, input().strip().split())
    weights.append(w)
    values.append(v)
    
dp = [0]*(W+1)
for i in range(N):
    for w in range(W, weights[i] - 1, -1):
        dp[w] = max(dp[w], values[i] + dp[w - weights[i]])

print(dp[W])

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env pypy
from __future__ import division, print_function
from collections import defaultdict, Counter, deque
from future_builtins import ascii, filter, hex, map, oct, zip
from itertools import imap as map, izip as zip, permutations, combinations, combinations_with_replacement
from __builtin__ import xrange as range
from math import ceil, factorial, log
from _continuation import continulet
from cStringIO import StringIO
from io import IOBase
import __pypy__
from bisect import bisect, insort, bisect_left, bisect_right
from fractions import Fraction
from functools import reduce
import string
import sys
import os
import re
inf = float('inf')
mod_ = int(1e9) + 7
mod = 998244353

def factors(n):
    from functools import reduce
    return set(reduce(list.__add__, ([i, n//i] for i in range(1, int(n**0.5) + 1) if n % i == 0)))

def sieve(m):
    n=1
    primes = {}
    arr=set([])
    for i in range(2, int(m ** 0.5) + 1):
        a = n // i
        b = m // i
        for k in range(max(2, a), b + 1):
            c = i * k
            primes[c] = 1

    for i in range(max(n, 2), m + 1):
        if i not in primes:
            arr.add(i)

    return arr


class DisjointSetUnion:
    def __init__(self, n):
        self.parent = list(range(n))
        self.size = [1] * n
        self.num_sets = n
 
    def find(self, a):
        acopy = a
        while a != self.parent[a]:
            a = self.parent[a]
        while acopy != a:
            self.parent[acopy], acopy = a, self.parent[acopy]
        return a
 
    def union(self, a, b):
        a, b = self.find(a), self.find(b)
        if a != b:
            if self.size[a] < self.size[b]:
                a, b = b, a
 
            self.num_sets -= 1
            self.parent[b] = a
            self.size[a] += self.size[b]
 
    def set_size(self, a):
        return self.size[self.find(a)]
 
    def __len__(self):
        return self.num_sets


def main():
    n,W=map(int,input().split())
    wt=[]
    val=[]
    for i in range(n):
        w,v=map(int,input().split())
        wt.append(w)
        val.append(v)
    t=[[-1 for i in range(W+2)] for j in range(n+2)]
    def knapsack(wt,W,val,n):
        if n==0 or W==0:
            return 0
        if t[n][W]!=-1:
            return t[n][W]
        if wt[n-1]<=W:
            t[n][W] = max(val[n-1]+knapsack(wt,W-wt[n-1],val,n-1),knapsack(wt,W,val,n-1))
            return t[n][W]
        else:
            t[n][W] = knapsack(wt,W,val,n-1)
            return t[n][W]
    print(knapsack(wt,W,val,n))










        

        
    




    



# region fastio

BUFSIZE = 8192

class FastI(IOBase):
    def __init__(self, file):
        self._fd = file.fileno()
        self._buffer = StringIO()
        self.newlines = 0

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count("\n") + (not b)
            ptr = self._buffer.tell()
            self._buffer.seek(0, 2), self._buffer.write(b), self._buffer.seek(ptr)
        self.newlines -= 1
        return self._buffer.readline()


class FastO(IOBase):
    def __init__(self, file):
        self._fd = file.fileno()
        self._buffer = __pypy__.builders.StringBuilder()
        self.write = lambda s: self._buffer.append(s)

    def flush(self):
        os.write(self._fd, self._buffer.build())
        self._buffer = __pypy__.builders.StringBuilder()


def print(*args, **kwargs):
    sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
    at_start = True
    for x in args:
        if not at_start:
            file.write(sep)
        file.write(str(x))
        at_start = False
    file.write(kwargs.pop("end", "\n"))
    if kwargs.pop("flush", False):
        file.flush()

def gcd(x, y):
    while y:
        x, y = y, x % y
    return x

sys.stdin, sys.stdout = FastI(sys.stdin), FastO(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")

# endregion

if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env pypy
from __future__ import division, print_function
from collections import defaultdict, Counter, deque
from future_builtins import ascii, filter, hex, map, oct, zip
from itertools import imap as map, izip as zip, permutations, combinations, combinations_with_replacement
from __builtin__ import xrange as range
from math import ceil, factorial, log
from _continuation import continulet
from cStringIO import StringIO
from io import IOBase
import __pypy__
from bisect import bisect, insort, bisect_left, bisect_right
from fractions import Fraction
from functools import reduce
import string
import sys
import os
import re
inf = float('inf')
mod_ = int(1e9) + 7
mod = 998244353

def factors(n):
    from functools import reduce
    return set(reduce(list.__add__, ([i, n//i] for i in range(1, int(n**0.5) + 1) if n % i == 0)))

def sieve(m):
    n=1
    primes = {}
    arr=set([])
    for i in range(2, int(m ** 0.5) + 1):
        a = n // i
        b = m // i
        for k in range(max(2, a), b + 1):
            c = i * k
            primes[c] = 1

    for i in range(max(n, 2), m + 1):
        if i not in primes:
            arr.add(i)

    return arr


class DisjointSetUnion:
    def __init__(self, n):
        self.parent = list(range(n))
        self.size = [1] * n
        self.num_sets = n
 
    def find(self, a):
        acopy = a
        while a != self.parent[a]:
            a = self.parent[a]
        while acopy != a:
            self.parent[acopy], acopy = a, self.parent[acopy]
        return a
 
    def union(self, a, b):
        a, b = self.find(a), self.find(b)
        if a != b:
            if self.size[a] < self.size[b]:
                a, b = b, a
 
            self.num_sets -= 1
            self.parent[b] = a
            self.size[a] += self.size[b]
 
    def set_size(self, a):
        return self.size[self.find(a)]
 
    def __len__(self):
        return self.num_sets


def main():
    n,W=map(int,input().split())
    wt=[]
    val=[]
    for i in range(n):
        w,v=map(int,input().split())
        wt.append(w)
        val.append(v)
    def knapsack(wt,W,val,n):
        if n==0 or W==0:
            return 0
        if wt[n-1]<=W:
            return max(val[n-1]+knapsack(wt,W-wt[n-1],val,n-1),knapsack(wt,W,val,n-1))
        else:
            return knapsack(wt,W,val,n-1)
    print(knapsack(wt,W,val,n))










        

        
    




    



# region fastio

BUFSIZE = 8192

class FastI(IOBase):
    def __init__(self, file):
        self._fd = file.fileno()
        self._buffer = StringIO()
        self.newlines = 0

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count("\n") + (not b)
            ptr = self._buffer.tell()
            self._buffer.seek(0, 2), self._buffer.write(b), self._buffer.seek(ptr)
        self.newlines -= 1
        return self._buffer.readline()


class FastO(IOBase):
    def __init__(self, file):
        self._fd = file.fileno()
        self._buffer = __pypy__.builders.StringBuilder()
        self.write = lambda s: self._buffer.append(s)

    def flush(self):
        os.write(self._fd, self._buffer.build())
        self._buffer = __pypy__.builders.StringBuilder()


def print(*args, **kwargs):
    sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
    at_start = True
    for x in args:
        if not at_start:
            file.write(sep)
        file.write(str(x))
        at_start = False
    file.write(kwargs.pop("end", "\n"))
    if kwargs.pop("flush", False):
        file.flush()

def gcd(x, y):
    while y:
        x, y = y, x % y
    return x

sys.stdin, sys.stdout = FastI(sys.stdin), FastO(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")

# endregion

if __name__ == "__main__":
    main()