Similar Problems
Similar Problems not available
K Items With The Maximum Sum - Leetcode Solution
Companies:
LeetCode: K Items With The Maximum Sum Leetcode Solution
Difficulty: Easy
Problem Statement:
Given an array of integers nums and an integer k, return the maximum sum of k non-overlapping subarrays.
A subarray is contiguous part of an array.
Solution Approach:
The approach to solve this problem is to use dynamic programming and divide the problem into smaller sub-problems.
First, we need to calculate the prefix sum of the given array. The prefix sum of an array is the cumulative sum of the array from the first element to i-th element.
Then, we create a 2D array dp of size [k+1][n+1]. dp[i][j] stores the maximum sum of i non-overlapping subarrays of nums[0:j].
We initialize dp[i][j] to 0, if i=0 or j=0.
Then, we fill in the values of dp[i][j] using the following recurrence relationship:
dp[i][j] = max(dp[i][j-1], dp[i-1][l] + (prefix_sum[j] - prefix_sum[l])) where l is the index from where the i-th subarray starts. We iterate over all possible values of l from i-1 to j-1 and calculate the maximum sum.
The final answer will be stored in dp[k][n].
Code:
class Solution {
public int maxSumOfThreeSubarrays(int[] nums, int k) {
int n = nums.length;
int[] sum = new int[n+1];
int[][] dp = new int[4][n+1];
for (int i=0; i<n; i++) {
sum[i+1] = sum[i] + nums[i];
}
for (int i=1; i<=3; i++) {
for (int j=i*k; j<=n; j++) {
dp[i][j] = Math.max(dp[i][j-1], dp[i-1][j-k] + sum[j] - sum[j-k]);
}
}
return dp[3][n];
}
}
Time Complexity:
The time complexity of the above code is O(nk) as we are filling in the dp array of size [k+1][n+1] and we are iterating over k values and n values.
Space Complexity:
The space complexity of the above code is O(n) as we are using a prefix sum array of size n+1 and a dp array of size [4][n+1].
K Items With The Maximum Sum Solution Code
1