Map Reduce

Open this Gdrive folder, open the Jupiter Notebook and let us execute the command together.

Then, let’s do the exercise at the bottom of the notebook.

Dynamic Programming exercise

Solve this exercise on the unbounded knapsack problem from Hackerrank: https://www.hackerrank.com/challenges/unbounded-knapsack/problem?isFullScreen=true

Given an array of integers and a target sum, determine the sum nearest to but not exceeding the target that can be created. To create the sum, use any element of your array zero or more times.

For example, if and your target sum is , you might select , or . In this case, you can arrive at exactly the target.

Example with and

In dynamic programming we use the solutions of subproblems to build the solution to the problem. Hence, we build a table like this one to understand the optimal substructure property:

Capacity (i)dp[0]dp[1]dp[2]dp[3]dp[4]dp[5]dp[6]dp[7]dp[8]dp[9]dp[10]dp[11]
Initial000000000000
Value 200224466881010
Value 300234567891011
Value 400234567891011

Explanation of the table

  1. Initialization: The dp array is initialized to 0.
  2. Value 2: Update dp[i] for each ( i ) from 1 to 10, choosing the maximum between dp[i] and dp[i - 2] + 2.
  3. Value 3: Update dp[i] for each ( i ) from 3 to 11, choosing the maximum between dp[i] and dp[i - 3] + 3.
  4. Value 4: Update dp[i] for each ( i ) from 4 to 11, choosing the maximum between dp[i] and dp[i - 4] + 4.

The final array shows that the maximum value obtainable for a capacity of ( k = 11 ) is 11.