We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
- Max Array Sum
- Discussions
Max Array Sum
Max Array Sum
Sort by
recency
|
491 Discussions
|
Please Login in order to post a comment
Using an additional array
def max_sum_non_adjacent(arr): if not arr: return 0 if len(arr) == 1: return arr[0]
Space complexity O(1) and time complexity O(n) Many answers here have space complexity O(n)
very straightforward dynamic programming question, O(n)
Solution: we start from the last element and we try to see if that element belongs to the max subset group. There can be 4 scenarios: * element belongs * adjancent elements belongs instead * element belongs with non-adjacent element * non-adjacebnt elemnt belongs instead * none belong, but that can be taken care of by making it recursively check what's best for the next step. Here's the code: