0

I was trying out some dynamic programming problems. I came across the following problems:

1. Maximum (consecutive) subset-sum
Finding the maximum sum of any consecutive set of elements in the given input array.
One possible solution is as follows:

def max_subarray_sum(arr):
    curr_sum = arr[0]
    max_so_far = arr[0]

    for num in arr[1:]:
        curr_sum = max(num, curr_sum + num)
        max_so_far = max(curr_sum, max_so_far)
    return max_so_far

2. Maximum non-adjacent elements subset-sum
Given an array of integers, find the subset of non-adjacent elements with the maximum sum. Calculate the sum of that subset. hackerrank link
One possible solution in python is as follows:

def maxSubsetSum(arr): 
    second_last_max_sum = arr[0]  
    last_max_sum = max(arr[0], arr[1])
    for num in arr[2:]: 
        curr_max_sum = max(num, last_max_sum, second_last_max_sum + num)
        second_last_max_sum = last_max_sum
        last_max_sum = curr_max_sum
    return last_max_sum

The solution to the first problem involves two max(), while that for the second involves single max(). So, I was guessing if I can somehow build logic with just single max() for the first problem, say by changing arguments to that single max() like for the second problem.

Q1. After considerable pondering, I came to the conclusion that I cannot because of the constraint in the first problem: sub-array need to be formed by consecutive numbers. Am I right with this?

Q2. Also, can I generalize this further, that is, what "kinds" of problems can be solved with just single max() and which kinds of problems require more than one max()? Or in other words, what are the "characteristics" of constraints on subarray that can be solved in single max() and of those that need at least two max()?

Mahesha999
  • 22,693
  • 29
  • 116
  • 189
  • I think by `max()` you are referring to comparison operations in general. For Q2, there are a large number of problems where the time complexity analysis focuses on the number of comparisons. However they only look at asymptotic numbers and whether you have a single or two comparisons in a for-loop is irrelevant. I don't think there is any analysis on these "characteristics" since this does not seem to have any theoretical significance. – Vaibhav G. Dec 07 '21 at 21:07
  • why is it important? both `max`-es in the first problem are over 2 elements and thus have constant complexity. Eliminating one of them won't change the big-O – Marat Dec 07 '21 at 21:08
  • btw, the first solution doesn't seem right – Marat Dec 07 '21 at 21:10
  • I was just thinking in logical (or better, logic building) point of view and not from the point of view of time complexity. – Mahesha999 Dec 07 '21 at 21:23

0 Answers0