Advertisement
Kali_prasad

A20250407b_Google_dp

Apr 8th, 2025
340
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.08 KB | None | 0 0
  1.  
  2.  
  3. '''
  4.  
  5. lets say you are given an n array integers
  6. task is to find the max sum you can make through your journey from 1st to last index
  7.  
  8. however at each index you can take that element and add it to your sum or leave it
  9.  
  10. but if you add it to your sum , for sure you cannot pick the next k elements to add it to your sum
  11.  
  12. -----------------------------------------------------------------------------------------------------
  13. important thing to be noted here is -
  14.  
  15. lets solve this with dp
  16.  
  17. here at each index you have 2 choices ,and either can result in max answer
  18.  
  19. so lets make them as dp state
  20.  
  21. not take 0 and take 1
  22.  
  23. lets say
  24.  
  25. you dont want to take current element
  26. now you are free to use the not taken dp instance of i-1 and taken dp instance of i-1
  27.  
  28. dp[i][0] = max(dp[i-1][0],dp[i-1][1])
  29.  
  30. what if
  31.  
  32. you want to take current element
  33.  
  34. you can take it but if you wanted to take it for sure last k elements might not be picked up
  35. so you can only use prev of k elements instances before
  36. (you cannot even use dp[i-1][0]),because you are not sure that it might be made up of dp[i-2][1]
  37. which is i-k -1
  38.  
  39.  
  40. now at i-k-1 instance you can choose taken dp instance or not taken dp instance both are allowed
  41.  
  42. so
  43. dp[i][1] = arr[i] + max(dp[i-k-1][0],dp[i-k-1][1])
  44.  
  45.  
  46. -----------------------------------------------------------------------------------------------------
  47. input -
  48.  
  49. 5 50 100 -1 -2 5 8 8
  50. 2
  51.  
  52. output -
  53.  
  54. 108
  55. '''
  56.  
  57. arr = list(map(int,input().split()))
  58. k = int(input())
  59.  
  60. #for 0 to k-1 elements we need to run a loop to fill the states
  61. #they wont be having i-k-1 indices so dp[i][1] for these indices will be simply arr[i]
  62. #and again dp[i][0] is normal again which is max(dp[i-1][0],dp[i-1][1])
  63. dp = [[0,0] for i in range(len(arr))]
  64. lastInd = len(dp)-1
  65. for i in range(len(arr)):
  66.     #if i ele is taken
  67.     if i <= k:
  68.         dp[i][1] = arr[i]
  69.     else:
  70.         dp[i][1] = arr[i] + max(dp[i-k-1][0],dp[i-k-1][1])
  71.  
  72.     #if i is not taken
  73.     if i>0:
  74.         dp[i][0] = max(dp[i-1][0],dp[i-1][1])
  75.    
  76. # print(dp)
  77.  
  78. print(max(dp[lastInd][0],dp[lastInd][1]))
  79.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement