Question

Consider a sequence of 14 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 subsequence sum S(i,j)=∑k=ijA[k]S(i, j) = \sum_{k=i}^j A[k]. Determine the maximum of S(i,j)S(i, j), where 0≤i≤j<140 \le i \le j < 14. (Divide and conquer approach may be used.)

Answer: ________.

Official answer and solution
Official answer
29
From
Official GATE 2019 answer key

Solution

Use Kadane's algorithm to compute the maximum contiguous subarray sum in linear time.

The given array of 14 elements is:

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 compute the maximum subarray sum using Kadane's algorithm, maintaining current_sum and max_so_far:

  • k=0,A[0]=−5k = 0, A[0] = -5: curr=−5,max=−5\text{curr} = -5, \text{max} = -5
  • k=1,A[1]=−10k = 1, A[1] = -10: curr=−10,max=−5\text{curr} = -10, \text{max} = -5
  • k=2,A[2]=6k = 2, A[2] = 6: curr=6,max=6\text{curr} = 6, \text{max} = 6
  • k=3,A[3]=3k = 3, A[3] = 3: curr=6+3=9,max=9\text{curr} = 6 + 3 = 9, \text{max} = 9
  • k=4,A[4]=−1k = 4, A[4] = -1: curr=9−1=8,max=9\text{curr} = 9 - 1 = 8, \text{max} = 9
  • k=5,A[5]=−2k = 5, A[5] = -2: curr=8−2=6,max=9\text{curr} = 8 - 2 = 6, \text{max} = 9
  • k=6,A[6]=13k = 6, A[6] = 13: curr=6+13=19,max=19\text{curr} = 6 + 13 = 19, \text{max} = 19
  • k=7,A[7]=4k = 7, A[7] = 4: curr=19+4=23,max=23\text{curr} = 19 + 4 = 23, \text{max} = 23
  • k=8,A[8]=−9k = 8, A[8] = -9: curr=23−9=14,max=23\text{curr} = 23 - 9 = 14, \text{max} = 23
  • k=9,A[9]=−1k = 9, A[9] = -1: curr=14−1=13,max=23\text{curr} = 14 - 1 = 13, \text{max} = 23
  • k=10,A[10]=4k = 10, A[10] = 4: curr=13+4=17,max=23\text{curr} = 13 + 4 = 17, \text{max} = 23
  • k=11,A[11]=12k = 11, A[11] = 12: curr=17+12=29,max=29\text{curr} = 17 + 12 = 29, \text{max} = 29
  • k=12,A[12]=−3k = 12, A[12] = -3: curr=29−3=26,max=29\text{curr} = 29 - 3 = 26, \text{max} = 29
  • k=13,A[13]=0k = 13, A[13] = 0: curr=26+0=26,max=29\text{curr} = 26 + 0 = 26, \text{max} = 29

The maximum contiguous subsequence sum is 2929, achieved by subarray from index 2 to index 11:

6+3+(−1)+(−2)+13+4+(−9)+(−1)+4+12=296 + 3 + (-1) + (-2) + 13 + 4 + (-9) + (-1) + 4 + 12 = 29
Final answer

29

The answer is the one in the official GATE answer key. The solution is this site's own explanation.

Source

Paper
GATE 2019 Computer Science and Information Technology (CS)
Question
35 of 65, printed as CS Q.25
Section
Computer Science and Information Technology

Report an error in this question

GATE questions are the work of the organising institutes. This site is independent and is not affiliated with them.