【leetcode】689. Maximum Sum of 3 Non-Overlapping Subarrays

题目如下:

In a given array nums of positive integers, find three non-overlapping subarrays with maximum sum.

Each subarray will be of size k, and we want to maximize the sum of all 3*k entries.

Return the result as a list of indices representing the starting position of each interval (0-indexed). If there are multiple answers, return the lexicographically smallest one.

Example:

Input: [1,2,1,2,6,7,5,1], 2
Output: [0, 3, 5]
Explanation: Subarrays [1, 2], [2, 6], [7, 5] correspond to the starting indices [0, 3, 5].
We could have also taken [2, 1], but an answer of [1, 3, 5] would be lexicographically larger.

Note:

  • nums.length will be between 1 and 20000.
  • nums[i] will be between 1 and 65535.
  • k will be between 1 and floor(nums.length / 3).

解题思路:本题如果只要求求出三段子数组的和的最大值,那会简单很多。记total[i]为arr[i:i+k]段的和,dp_left_max[i]为nums[:i]区间内长度为k的子数组的和的最大值,dp_right_max[i]为nums[i:len(nums)]区间内长度为k的子数组的和的最大值,很显然如果中间段的子数组的下标为k,那么可以得到三段和的最大长度的表达:total[i] + dp_left_max[i-k] + dp_right_max[i+k] 。只要遍历数组arr,即可求出最大值。求出后就是计算出左边以及右边最大值出现时的最小下标,这个可以通过二分查找实现。

代码如下:

class Solution(object):
    def maxSumOfThreeSubarrays(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: List[int]
        """
        count = sum(nums[:k])
        total = [count]
        total_inx = {}
        total_inx[count] = [0]
        dp_left_max = [count]
        dp_left_max_count = count
        for i in range(k, len(nums)):
            count -= nums[i - k]
            count += nums[i]
            total += [count]
            total_inx[count] = total_inx.setdefault(count,[]) + [i-k + 1]
            dp_left_max_count = max(dp_left_max_count,count)
            dp_left_max.append(dp_left_max_count)

        reverse_num = nums[::-1]
        count = sum(reverse_num[:k])
        dp_right_max = [count]
        dp_right_max_count = count
        for i in range(k, len(reverse_num)):
            count -= reverse_num[i - k]
            count += reverse_num[i]
            dp_right_max_count = max(dp_right_max_count,count)
            dp_right_max.insert(0,dp_right_max_count)

        #print total
        #print total_inx
        #print dp_left_max
        #print dp_right_max

        max_sum = -float(‘inf‘)
        mid_inx = 0
        left_val = 0
        right_val = 0
        for i in range(k,len(nums)-k-k+1):
            count = total[i] + dp_left_max[i-k] + dp_right_max[i+k]
            if count > max_sum:
                mid_inx = i
                left_val = dp_left_max[i-k]
                right_val = dp_right_max[i+k]
                max_sum = count
        #print left_val,mid_inx,right_val

        left_inx = total_inx[left_val][0]
        import bisect
        right_inx = bisect.bisect_left(total_inx[right_val],mid_inx+k)
        return [left_inx,mid_inx,total_inx[right_val][right_inx]]

原文地址:https://www.cnblogs.com/seyjs/p/11616699.html

时间: 2024-08-18 11:28:47

【leetcode】689. Maximum Sum of 3 Non-Overlapping Subarrays的相关文章

【Leetcode】Minimum Path Sum

Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path. Note: You can only move either down or right at any point in time. 思路:简单的动态规划题目,设f(m, n)为从(0, 0)到达(m

【leetcode】998. Maximum Binary Tree II

题目如下: We are given the root node of a maximum tree: a tree where every node has a value greater than any other value in its subtree. Just as in the previous problem, the given tree was constructed from an list A (root = Construct(A)) recursively with

【LeetCode】113. Path Sum II 基于Java和C++的解法及分析

113. Path Sum II Total Accepted: 80509 Total Submissions: 284188 Difficulty: Medium Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum. For example: Given the below binary tree and sum = 22, 5 / 4 8

【LeetCode】Minimum Path Sum 解题报告

[题目] Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path. Note: You can only move either down or right at any point in time. [思路] 求从左上角到右下角的最小路径值,典型的动态规划

【LeetCode】1. Two Sum 解题报告

转载请注明出处:http://blog.csdn.net/crazy1235/article/details/51471280 Subject 出处:https://leetcode.com/problems/two-sum/ Given an array of integers, return indices of the two numbers such that they add up to a specific target. You may assume that each input

【UVA】108 - Maximum Sum(DP矩阵)

n^3的复杂度计算最小子矩阵,用了最大连续和的DP算法. 14273282 108 Maximum Sum Accepted C++ 0.013 2014-09-27  #include<cstdio> #include<cstring> #include<algorithm> using namespace std; const int INF = 1 << 30; const int maxn = 127 + 3; int mat[maxn][maxn]

【LeetCode】039. Combination Sum

题目: Given a set of candidate numbers (C) (without duplicates) and a target number (T), find all unique combinations in C where the candidate numbers sums to T. The same repeated number may be chosen from C unlimited number of times. Note: All numbers

【LeetCode】053. Maximum Subarray

题目: Find the contiguous subarray within an array (containing at least one number) which has the largest sum. For example, given the array [-2,1,-3,4,-1,2,1,-5,4],the contiguous subarray [4,-1,2,1] has the largest sum = 6. 题解: 由于是连续子序列这个限制,所以如果k+1这个元素

【LeetCode】167. Two Sum II - Input array is sorted

Two Sum II - Input array is sorted Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number. The function twoSum should return indices of the two numbers such that they a