Similar Problems

Similar Problems not available

Maximum Subsequence Score - Leetcode Solution

Companies:

LeetCode:  Maximum Subsequence Score Leetcode Solution

Difficulty: Medium

Topics: greedy sorting heap-priority-queue array  

Problem Statement:

Given an integer array nums, you need to find the maximum possible sum of a contiguous subarray of the array.

Example 1:

Input: nums = [-2,1,-3,4,-1,2,1,-5,4] Output: 6 Explanation: The contiguous subarray [4,-1,2,1] has the largest sum = 6.

Example 2:

Input: nums = [1] Output: 1

Example 3:

Input: nums = [5,4,-1,7,8] Output: 23

Constraints:

1 <= nums.length <= 10^5 -10^4 <= nums[i] <= 10^4

Solution:

The problem can be efficiently solved using Kadane's algorithm, which is based on dynamic programming.

The basic idea of the algorithm is to iterate over the array and maintain two variables:

  1. max_sum_ending_here: Maximum sum of subarray ending at the current position i.

  2. max_sum_so_far: Maximum sum of subarray seen so far.

Initially, both variables are set to the first element of the array.

For each subsequent element, we calculate the current subarray sum using the maximum of:

  1. The current element.

  2. The sum of the current element and the sum of the subarray ending at the previous position.

We update the max_sum_ending_here variable accordingly.

Then we check if the value of max_sum_ending_here is greater than max_sum_so_far. If it is, then we update max_sum_so_far to max_sum_ending_here.

Finally, we return the value of max_sum_so_far.

The time complexity of the algorithm is O(N), where N is the length of the array, as we need to pass through the array only once.

Here is the Python implementation of the Kadane's algorithm:

def maxSubArray(nums: List[int]) -> int: max_sum_ending_here = max_sum_so_far = nums[0] for i in range(1, len(nums)): max_sum_ending_here = max(nums[i], nums[i] + max_sum_ending_here) max_sum_so_far = max(max_sum_so_far, max_sum_ending_here) return max_sum_so_far

This code can also be optimized by storing only the previous max_sum_ending_here instead of the entire array, as we need to know only the previous value to calculate the current one.

Hence, the space complexity of the optimized algorithm is O(1).

Maximum Subsequence Score Solution Code

1