- Related Questions & Answers
- Program to find maximum sum of two non-overlapping sublists in Python
- Program to find sum of k non-overlapping sublists whose sum is maximum in C++
- Maximum Sum of 3 Non-Overlapping Subarrays in C++
- Program to find minimum largest sum of k sublists in C++
- Program to find sum of the sum of all contiguous sublists in Python
- Program to find largest sum of non-adjacent elements of a list in Python
- Maximum Sum of Two Non-Overlapping Subarrays in C++
- Program to find the sum of the lengths of two nonoverlapping sublists whose sum is given in Python
- Program to find the sum of largest K sublist in Python
- Program to find number of sublists whose sum is given target in python
- Max sum of M non-overlapping subarrays of size K in C++
- Maximum sum two non-overlapping subarrays of given size in C++
- Program to find sum of medians of all odd length sublists in C++
- Program to Find K-Largest Sum Pairs in Python
- Program to find largest sum of any path of a binary tree in Python

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

Suppose we have a list of numbers called nums and another value k, we have to find the largest sum of three non-overlapping sublists of the given list of size k.

So, if the input is like nums = [2, 2, 2, -6, 4, 4, 4, -8, 3, 3, 3] k = 3, then the output will be 27, as we can select the sublists [2, 2, 2], [4, 4, 4], and [3, 3, 3], total sum is 27.

To solve this, we will follow these steps −

- P := [0]
- for each x in A, do
- insert P[-1] + x at the end of P

- Q := [P[i + K] - P[i] for i in range 0 to size of P - K]
- prefix := Q[from index 0 to end]
- suffix := Q[from index 0 to end]
- for i in range 0 to size of Q - 1, do
- prefix[i + 1] := maximum of prefix[i + 1], prefix[i]
- suffix[~(i + 1) ] := maximum of suffix[~(i + 1) ], suffix[~i]

- ret = (Q[i] + prefix[i - K] + suffix[i + K]) for each i in range K to size of Q - K - 1
- return maximum of ret

Let us see the following implementation to get better understanding −

class Solution: def solve(self, A, K): P = [0] for x in A: P.append(P[-1] + x) Q = [P[i + K] - P[i] for i in range(len(P) - K)] prefix = Q[:] suffix = Q[:] for i in range(len(Q) - 1): prefix[i + 1] = max(prefix[i + 1], prefix[i]) suffix[~(i + 1)] = max(suffix[~(i + 1)], suffix[~i]) return max(Q[i] + prefix[i - K] + suffix[i + K] for i in range(K, len(Q) - K)) ob = Solution() nums = [2, 2, 2, -6, 4, 4, 4, -8, 3, 3, 3] k = 3 print(ob.solve(nums, k))

[2, 2, 2, -6, 4, 4, 4, -8, 3, 3, 3], 3

27

Advertisements