Analyzing dynamic programming solutions to different maximum subarray problems

310 Views Asked by At

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()?

0

There are 0 best solutions below