leetcode 1043. Partition Array for Maximum Sum (python)
「這是我參與11月更文挑戰的第19天,活動詳情檢視:2021最後一次更文挑戰」
描述
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
Note:
1 <= arr.length <= 500
0 <= arr[i] <= 10^9
1 <= k <= arr.length
解析
根據題意,給定一個整數陣列 arr,將該陣列劃分為幾個長度至多為 k 的連續子陣列。 分割槽後,每個子陣列的值都變為該子陣列的最大值。題目要求我們分割槽後返回新陣列可能的最大和。 題意很清楚,結合例子一基本也就能完全理解題意了。
這道題是看了大神的解答才寫出來的,使用的是一維動態規劃陣列解答,文尾有大神推到連結
- 初始化長度為 len(arr) 的一維陣列, dp[i] 表示的就是 arr[:i] 經過操作後得到的最大和值,
- 遍歷 range(N) ,也就是遍歷 arr 中的所有元素位置索引 i ,再遍歷 range(i,max(-1, i-k),-1) 也就是可能的子陣列位置索引 j ,不斷更新當前子陣列的最大值 MAX,又不斷更新 dp[i] = max(dp[i], dp[j-1] + MAX*(i-j+1)) ,注意邊界條件的限制。
- 遍歷結束返回 dp[-1] 即為答案
解答
class Solution(object):
def maxSumAfterPartitioning(self, arr, k):
"""
:type arr: List[int]
:type k: int
:rtype: int
"""
N = len(arr)
dp = [0 for _ in range(N)]
for i in range(N):
MAX = 0
for j in range(i,max(-1, i-k),-1):
MAX = max(arr[j], MAX)
if j>=1:
dp[i] = max(dp[i], dp[j-1] + MAX*(i-j+1))
else:
dp[i] = max(dp[i], MAX*(i-j+1))
return dp[-1]
執行結果
Runtime: 408 ms, faster than 61.04% of Python online submissions for Partition Array for Maximum Sum.
Memory Usage: 13.4 MB, less than 94.81% of Python online submissions for Partition Array for Maximum Sum.
原題連結:http://leetcode.com/problems/partition-array-for-maximum-sum/
大神解釋:http://www.bilibili.com/video/BV143411z7ek
您的支援是我最大的動力
「其他文章」
- leetcode 2258. Escape the Spreading Fire(python)
- leetcode 2257. Count Unguarded Cells in the Grid(python)
- leetcode 2273. Find Resultant Array After Removing Anagrams(python)
- leetcode 1209. Remove All Adjacent Duplicates in String II(python)
- leetcode 1396. Design Underground System (python)
- leetcode 1679. Max Number of K-Sum Pairs (python)
- leetcode 216. Combination Sum III(python)
- 解決安裝 CUDA 10.0 報錯未安裝元件
- 解決安裝 anaconda 時報錯 failed to create menus
- anaconda 建立虛擬環境時報錯 HTTP errors 解決辦法
- 解決 could not load dynamic library cudart64_100.dll
- leetcode 2244. Minimum Rounds to Complete All Tasks(python)
- leetcode 2245. Maximum Trailing Zeros in a Cornered Path (python)
- leetcode 2241. Design an ATM Machine(python)
- leetcode 2240. Number of Ways to Buy Pens and Pencils (python)
- leetcode 2239. Find Closest Number to Zero (python)
- tensorflow 1.x 實戰教程(十一)—模型的儲存與恢復
- tensorflow 1.x 實戰教程(十)—迴圈神經網路
- tensorflow 1.x 實戰教程(八)—學習率衰減並在 TensorBoard 中顯示變數變化
- tensorflow 1.x 實戰教程(七)——加入 Dropout 的分類模型