LeetCode · Daily Question · 1186. Delete once to get the maximum sum of sub-arrays · Dynamic Programming

Author: Xiao Xun
Link: https://leetcode.cn/problems/maximum-subarray-sum-with-one-deletion/solutions/2321919/dong-tai-gui-hua-zhu-shi-chao-ji-xiang- x-cwvs/
Source: The copyright of LeetCode
belongs to the author. For commercial reprint, please contact the author for authorization, for non-commercial reprint, please indicate the source.

topic

 

example

 

train of thought

Title -> Given an array, you can delete at most one arbitrary element, and return the maximum sum of the subarrays

define dp[arrSize][2]

  • dp[i][0] means to select the maximum sum of the current element arr[i], and dp[i][1] means to delete the maximum sum of an element.
  • Since the meaning of the question requires that one element must be included, so initialize dp[0][0] = arr[0], dp[0][1] = 0, the initial value must contain one element, so it can only be arr[0], Initially delete an element and the sum must be 0.
  • The sum of the current position must depend on the state of the previous position, so the recursion direction must be from left to right
  • Recursion formula:
    • dp[i][0] = MAX(dp[i-1][0], 0) + arr[i]; If the sum of the previous position is less than 0, the current position is the beginning of the sub-array
    • dp[i][1] = MAX(dp[i-1][1] + arr[i], dp[i-1][0]); Deleting an element can be divided into deleting the current element and deleting the sub-array others Element, where dp[i-1][0] means to delete the current element, dp[i-1][1] + arr[i] means to delete other elements
  • Save the maximum value at each step

Code comments are super detailed

the code


#define MAX(a, b) ((a) > (b) ? (a) : (b))
int maximumSum(int* arr, int arrSize) {
    int max = arr[0];
    int dp[arrSize][2];
    dp[0][0] = arr[0];
    dp[0][1] = 0;//初始化
    for (int i = 1; i < arrSize; i++) {
        dp[i][0] = MAX(dp[i-1][0], 0) + arr[i];//选择当前位置
        dp[i][1] = MAX(dp[i-1][1] + arr[i], dp[i-1][0]);//删除一个元素
        max = MAX(max, MAX(dp[i][0], dp[i][1]));//取每一个子数组最大值
    }
    return max;
}


作者:小迅
链接:https://leetcode.cn/problems/maximum-subarray-sum-with-one-deletion/solutions/2321919/dong-tai-gui-hua-zhu-shi-chao-ji-xiang-x-cwvs/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

Guess you like

Origin blog.csdn.net/m0_64560763/article/details/131410943