
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Partition Array for Maximum Sum in Python
Suppose we have an integer array A, we have to partition the array into (contiguous) subarrays of length at most K. After partitioning, each subarray has their values changed to become the maximum value of that subarray. We have to find the largest sum of the given array after partitioning. So if input is like [1, 15, 7, 9, 2, 5, 10] and k = 3, then the output will be 84. This is because the array becomes [15, 15, 15, 9, 10, 10, 10]
To solve this, we will follow these steps −
- make one array dp of length same as A, and fill this with 0
- for i in range 0 to length of A - 1
- dp[i] = A[i] + dp[i - 1] if i – 1 >= 0 otherwise 0
- temp := A[i]
- for j in range 1 to k – 1
- if i – j >= 0
- index := i – j
- temp := max of temp and A[i - j]
- if index – 1 >= 0, then
- dp[i] := max of dp[i] and (temp*(i – index + 1) + dp[index - 1])
- otherwise dp[i] := max of dp[i] and 0
- if i – j >= 0
- return last element of dp
Let us see the following implementation to get better understanding −
Example
class Solution(object): def maxSumAfterPartitioning(self, A, K): dp = [0 for i in range(len(A))] for i in range(len(A)): dp[i] = A[i] + (dp[i-1] if i-1>=0 else 0) temp = A[i] for j in range(1,K): if i-j>=0: index = i-j temp = max(temp,A[i-j]) dp[i] = max(dp[i],temp*(i-index+1) + (dp[index-1] if index-1 >=0 else 0)) return dp[-1] ob = Solution() print(ob.maxSumAfterPartitioning([1,15,7,9,2,5,10],3))
Input
[1,15,7,9,2,5,10] 3
Output
84
- Related Articles
- Maximum average sum partition of an array in C++
- Partition Array Into Three Parts With Equal Sum in Python
- Array Partition I in Python
- Program to find maximum weighted sum for rotated array in Python
- Partition Equal Subset Sum in C++
- Program to find partition array into disjoint intervals in Python
- Maximum triplet sum in array in C++
- Maximum equlibrium sum in an array in C++
- Partition to K Equal Sum Subsets in C++
- Check if it possible to partition in k subarrays with equal sum in Python
- Maximum subarray sum in circular array using JavaScript
- Partition Array into Disjoint Intervals in C++
- Binary Tree Maximum Path Sum in Python
- Find a partition point in array in C++
- Find Two Array Elements Having Maximum Sum in Java?

Advertisements