Skip to content
Official PYQ · 2019

GATE CS 2019 Q25 — Algorithm Design: Greedy Techniques

Explain with AI
Consider a sequence of 1414 elements: A=[−5,−10,6,3,−1,−2,13,4,−9,−1,4,12,−3,0]A=[-5, -10, 6, 3, -1, -2, 13, 4, -9, -1, 4, 12, -3, 0]. The sequence sum S(i,j)=Σk=ijA[k]S(i,j) = \Sigma_{k=i}^j A[k]. Determine the maximum of S(i,j)S(i,j), where 0≤i≤j<140 \leq i \leq j <14. (Divide and conquer approach may be used.)

Answer: ___________
View worked solution

Answer: 29

This is the classic Maximum Subarray Sum problem. We can solve this efficiently in O(n)O(n) time using Kadane's Algorithm.

Kadane's Algorithm Steps

Let AA be the given array of size 14:

A=[−5,−10,6,3,−1,−2,13,4,−9,−1,4,12,−3,0]A = [-5, -10, 6, 3, -1, -2, 13, 4, -9, -1, 4, 12, -3, 0]

We maintain two variables:

  • current_max: The maximum subarray sum ending at the current position.
  • global_max: The overall maximum subarray sum found so far.

We iterate through the array from index 00 to 1313 using the recurrence:

current_max[k]=max⁡(A[k],current_max[k−1]+A[k])\text{current\_max}[k] = \max(A[k], \text{current\_max}[k-1] + A[k])

Index (kk) Element A[k]A[k] current_max global_max
0-5-5-5
1-10-10-5
2666
3399
4-189
5-269
6131919
742323
8-91423
9-11323
1041723
11122929
12-32629
1302629

The maximum subarray sum is achieved by the subarray from index 22 to 1111:

A[2…11]=[6,3,−1,−2,13,4,−9,−1,4,12]A[2 \dots 11] = [6, 3, -1, -2, 13, 4, -9, -1, 4, 12]

Sum=6+3−1−2+13+4−9−1+4+12=29\text{Sum} = 6 + 3 - 1 - 2 + 13 + 4 - 9 - 1 + 4 + 12 = 29

Thus, the maximum of S(i,j)S(i,j) is 29.

Free practice · Your answers on this page are not saved.

Published
Report a correction
Keep exploringMore Algorithm Design: Greedy Techniques questions