Aziz Daa Assignment
Aziz Daa Assignment
Assignment
Ans:
1. Problem: Partition a Set into Two Equal Sums
• Given a set of positive integers, determine if it can be partitioned into
two parts having equal sum using dynamic programming approaches.
Let,
S = {1, 5, 11, 5}
• Algorithm:
Step 1. Calculate the total sum of the set S. [O(n)]
Step 2. If the total sum is odd, return False. [O(1)]
Step 3. Set target to half of the total sum. [O(1)]
Step 4. Create a set possible_sums and initialize it with {0} (sum of 0 is
possible). [O(1)]
Step 5. For each element in set S: [O(n x target)]
• Create a temporary set n_sums to store new sums. [O(1)]
• For each sum in possible_sums, add current element to it and add
the result to n_sums. [O(n x target)]
• Add all sums in n_sums to possible_sums. [O(target)]
Step 6. After processing all elements, check if target is in
possible_sums. [O(1)]
• If target is in possible_sums, return True. [O(1)]
• If target is not in possible_sums, return False. [O(1)]
• Complexity:
Step 1: [O(n)]
Step 2: [O(1)]
Step 3: [O(1)]
Step 4: [O(1)]
Step 5: [O(n x target)]
Step 6: [O(1)]
Total time complexity = O(n) + O(1) + O(1) + O(1) + O(n x target) +O(1)
= O(n x target)
• You are given n items, each with a weight and a value, and a knapsack with a
weight capacity W. You need to determine the maximum value you can carry in
the knapsack without exceeding the weight capacity.
• Algorithm:
• If n == 0 or W == 0, return 0
• If memo [n] [W] is not null, return memo [n] [W]
• If weights [n-1] > W, call knapsack (n-1, W, weights, values, memo).
• Otherwise
• Call knapsack (n-1, W, weights, values, memo).
• Store the maximum of the two results in memo[n][W].
• Return memo [n][W].
• Time Complexity:
Step 1. O(1)
• O(1)
• O(1)
• O(1)
• O(1)
• O(1)
• O(1)
Step 2. O( n x W)
• O(1)
• O( n x W)
• O(n x W)
= O( n x W)