What is the space complexity of the following dynamic programming implementation of the balanced partition problem?
#include<stdio.h>
int balanced_partition(int *arr, int len)
{
int sm = 0, i, j;
for(i = 0;i < len; i++)
sm += arr[i];
if(sm % 2 != 0)
return 0;
int ans[sm/2 + 1][len + 1];
for(i = 0; i <= len; i++)
ans[0][i] = 1;
for(i = 1; i <= sm/2; i++)
ans[i][0] = 0;
for(i = 1; i <= sm/2; i++)
{
for(j = 1;j <= len; j++)
{
ans[i][j] = ans[i][j-1];
if(i >= arr[j - 1])
ans[i][j] = ans[i][j] || ans[i - arr[j - 1]][j - 1];
}
}
return ans[sm/2][len];
}
int main()
{
int arr[] = {3, 4, 5, 6, 7, 1}, len = 6;
int ans = balanced_partition(arr,len);
if(ans == 0)
printf("false");
else
printf("true");
return 0;
}
#include<stdio.h>
int balanced_partition(int *arr, int len)
{
int sm = 0, i, j;
for(i = 0;i < len; i++)
sm += arr[i];
if(sm % 2 != 0)
return 0;
int ans[sm/2 + 1][len + 1];
for(i = 0; i <= len; i++)
ans[0][i] = 1;
for(i = 1; i <= sm/2; i++)
ans[i][0] = 0;
for(i = 1; i <= sm/2; i++)
{
for(j = 1;j <= len; j++)
{
ans[i][j] = ans[i][j-1];
if(i >= arr[j - 1])
ans[i][j] = ans[i][j] || ans[i - arr[j - 1]][j - 1];
}
}
return ans[sm/2][len];
}
int main()
{
int arr[] = {3, 4, 5, 6, 7, 1}, len = 6;
int ans = balanced_partition(arr,len);
if(ans == 0)
printf("false");
else
printf("true");
return 0;
}A. O(sum)
B. O(n)
C. O(sum * n)
D. O(sum + n)
Answer: Option C
What is the main principle behind Dynamic Programming (DP)?
A. Recursion with memoization.
B. Greedy approach.
C. Divide and conquer.
D. Overlapping subproblems and optimal substructure.
Which of the following problems can be solved using Dynamic Programming?
A. Binary Search
B. Depth-First Search
C. Longest Common Subsequence
D. Quick Sort
What is the key advantage of using Dynamic Programming over plain recursion?
A. It makes the code simpler.
B. It reduces the time complexity by storing results of subproblems.
C. It uses more memory.
D. It makes the code simpler.
In the context of Dynamic Programming, what does the term "memoization" refer to?
A. Using a stack to manage function calls.
B. A method for dividing problems.
C. Storing intermediate results to avoid redundant calculations.
D. A technique to speed up sorting.

Join The Discussion