Consider the following implementation of Kadane's algorithm:
#include<stdio.h>
int max_num(int a, int b)
{
if(a > b)
return a;
return b;
}
int kadane_algo(int *arr, int len)
{
int ans = 0, sum = 0, idx;
for(idx =0; idx < len; idx++)
{
sum = max_num(0,sum + arr[idx]);
ans = max_num(sum,ans);
}
return ans;
}
int main()
{
int arr[] = {-2, -3, -3, -1, -2, -1, -5, -3},len = 8;
int ans = kadane_algo(arr,len);
printf("%d",ans);
return 0;
}
What changes should be made to the Kadane's algorithm so that it produces the right output even when all array elements are negative?
Change 1 = Line 10: int sum = arr[0], ans = arr[0]
Change 2 = Line 13: sum = max_num(arr[idx],sum+arr[idx])
#include<stdio.h>
int max_num(int a, int b)
{
if(a > b)
return a;
return b;
}
int kadane_algo(int *arr, int len)
{
int ans = 0, sum = 0, idx;
for(idx =0; idx < len; idx++)
{
sum = max_num(0,sum + arr[idx]);
ans = max_num(sum,ans);
}
return ans;
}
int main()
{
int arr[] = {-2, -3, -3, -1, -2, -1, -5, -3},len = 8;
int ans = kadane_algo(arr,len);
printf("%d",ans);
return 0;
}Change 1 = Line 10: int sum = arr[0], ans = arr[0]
Change 2 = Line 13: sum = max_num(arr[idx],sum+arr[idx])A. Only Change 1 is sufficient
B. Only Change 2 is sufficient
C. Both Change 1 and Change 2 are necessary
D. No change is required
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