Skip to content

Latest commit

 

History

History
136 lines (109 loc) · 3.12 KB

File metadata and controls

136 lines (109 loc) · 3.12 KB

中文文档

Description

Given an integer array arr, 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.

Return the largest sum of the given array after partitioning. Test cases are generated so that the answer fits in a 32-bit integer.

 

Example 1:

Input: arr = [1,15,7,9,2,5,10], k = 3
Output: 84
Explanation: arr becomes [15,15,15,9,10,10,10]

Example 2:

Input: arr = [1,4,1,5,7,3,6,1,9,9,3], k = 4
Output: 83

Example 3:

Input: arr = [1], k = 1
Output: 1

 

Constraints:

  • 1 <= arr.length <= 500
  • 0 <= arr[i] <= 109
  • 1 <= k <= arr.length

Solutions

Python3

class Solution:
    def maxSumAfterPartitioning(self, arr: List[int], k: int) -> int:
        n = len(arr)
        f = [0] * (n + 1)
        for i in range(n):
            mx = 0
            for j in range(i, max(-1, i - k), -1):
                mx = max(mx, arr[j])
                t = mx * (i - j + 1) + f[j]
                f[i + 1] = max(f[i + 1], t)
        return f[n]

Java

class Solution {
    public int maxSumAfterPartitioning(int[] arr, int k) {
        int n = arr.length;
        int[] f = new int[n + 1];
        for (int i = 0; i < n; ++i) {
            int mx = 0;
            for (int j = i; j >= Math.max(0, i - k + 1); --j) {
                mx = Math.max(mx, arr[j]);
                int t = mx * (i - j + 1) + f[j];
                f[i + 1] = Math.max(f[i + 1], t);
            }
        }
        return f[n];
    }
}

C++

class Solution {
public:
    int maxSumAfterPartitioning(vector<int>& arr, int k) {
        int n = arr.size();
        int f[n + 1];
        memset(f, 0, sizeof f);
        for (int i = 0; i < n; ++i) {
            int mx = 0;
            for (int j = i; j >= max(0, i - k + 1); --j) {
                mx = max(mx, arr[j]);
                int t = mx * (i - j + 1) + f[j];
                f[i + 1] = max(f[i + 1], t);
            }
        }
        return f[n];
    }
};

Go

func maxSumAfterPartitioning(arr []int, k int) int {
	n := len(arr)
	f := make([]int, n+1)
	for i := 0; i < n; i++ {
		mx := 0
		for j := i; j >= max(0, i-k+1); j-- {
			mx = max(mx, arr[j])
			t := mx*(i-j+1) + f[j]
			f[i+1] = max(f[i+1], t)
		}
	}
	return f[n]
}

func max(a, b int) int {
	if a > b {
		return a
	}
	return b
}

...