Similar Problems

Similar Problems not available

Find Subsequence Of Length K With The Largest Sum - Leetcode Solution

Companies:

LeetCode:  Find Subsequence Of Length K With The Largest Sum Leetcode Solution

Difficulty: Easy

Topics: hash-table sorting heap-priority-queue array  

Problem Statement:

Given an array nums of integers, find a subsequence of length k with the largest sum.

A subsequence is a sequence that can be derived from an array by deleting some or no elements without changing the order of the remaining elements.

Example:

Input: nums = [10,2,-10,5,20], k = 2 Output: 30 Explanation: The subsequence [10, 20] has the largest sum = 30.

Solution:

The given problem is a variation of the sliding window problem. The length of the subsequence is fixed to k, so we can use a sliding window approach to find the subsequence with the largest sum.

First, we will calculate the sum of the first k elements of the array and store it as the current maximum sum. Then, we will slide the window by one element at a time and recalculate the sum of the new window. If the new sum is greater than the current maximum sum, we will update the current maximum sum.

Algorithm:

  1. Calculate the sum of the first k elements of the array and store it as the current maximum sum.
  2. Create a variable called current sum and initialize it to the current maximum sum.
  3. Loop from k to the end of the array.
  4. Subtract the element that is leaving the window and add the element that is entering the window to the current sum.
  5. If the current sum is greater than the current maximum sum, update the current maximum sum.
  6. Return the current maximum sum.

Python code implementation:

def maxSum(nums, k): currMax = sum(nums[:k]) # step 1

currSum = currMax    # step 2

for i in range(k, len(nums)):   # step 3
    
    currSum += nums[i] - nums[i-k]   # step 4
    
    if currSum > currMax:   # step 5
        
        currMax = currSum
        
return currMax   # step 6

Example testcases:

  1. Testcase 1: nums = [10,2,-10,5,20], k = 2 Expected Output: 30

  2. Testcase 2: nums = [1,4,2,10,23,3,1,0,20], k = 4 Expected Output: 39

  3. Testcase 3: nums = [8,-1,-6,-5,-7,8,3,-4,2,9], k = 7 Expected Output: 24

Note: The time complexity of the above solution is O(n), where n is the length of the input array nums.

Find Subsequence Of Length K With The Largest Sum Solution Code

1