Leetcode53-Maximum Subarray(Python3)

53. 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.

题解:

输入一个数组,求数组的连续子数组中,最大的一段的和;
原问题:n个数的数组(nums)的最大子段和;
子问题:
一个数的数组的最大子段和:dp[0] = nums[0];
两个数的数组的最大子段和:两种情况,加上第一个数(dp[0] + nums[1])或不加上第一个数(nums[1]):dp[1] = max(dp[0] + nums[1], nums[1]);其实也就相当于是以第二个数作为子段结尾的情况下的最优解;然后再取max(dp[0], dp[1])
确认状态:
n个数的数组的最大子段和:
以nums[n-1]结尾的最大子段和前n-1个子段最大和比较,取最大值;
动态规划状态转移方程:
以第n个数结尾的最大子段和:dp[n-1] = (dp[n-2] + nums[n-1], nums[n-1])
边界状态:dp[0] = nums[0];
最后输出:max(dp[0],dp[1],.....dp[n-1])

My Solution(C/C++)

#include <cstdio>
#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

class Solution {
public:
    int maxSubArray(vector<int> &nums) {
        vector<int> dp(nums.size() + 3, 0);
        if (nums.size() == 0) {
            return 0;
        }
        dp[0] = nums[0];
        int max_dp = dp[0];
        for (int i = 1; i < nums.size(); i++) {
            dp[i] = max(dp[i - 1] + nums[i], nums[i]);
            if (max_dp < dp[i]) {
                max_dp = dp[i];
            }
        }
        return max_dp;
    }
};

int main() {
    vector<int> nums;
    nums.push_back(-2);
    nums.push_back(1);
    nums.push_back(-3);
    nums.push_back(4);
    nums.push_back(-1);
    nums.push_back(2);
    nums.push_back(1);
    nums.push_back(-5);
    nums.push_back(4);
    Solution s;
    printf("最大子段和:%d", s.maxSubArray(nums));
    return 0;
}

结果

最大子段和:6

My Solution 1(Python)

class Solution(object):
    def maxSubArray(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        sum, result = 0, 0
        for i in range(len(nums)):
            sum += nums[i]
            if sum < 0:
                sum = 0
            else:
                result = max(sum, result)
        if result == 0:
            return max(nums)
        return result

My Solution 2(Python)

class Solution:
    def maxSubArray(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        dp = []
        if len(nums) == 0:
            return []
        dp.append(nums[0])
        max_dp = dp[-1]
        for i in range(1, len(nums)):
            dp.append(max(dp[i-1] + nums[i], nums[i]))
            if max_dp < dp[-1]:
                max_dp = dp[-1]
        return max_dp

Reference (转)

Python:
class Solution(object):
    def maxSubArray(self, nums):
        for i in xrange(1,len(nums)):nums[i]=max(nums[i], nums[i]+nums[i-1])
        return max(nums)
Java:
class Solution {
public int maxSubArray(int[] A) {
        int n = A.length;
        int[] dp = new int[n];//dp[i] means the maximum subarray ending with A[i];
        dp[0] = A[0];
        int max = dp[0];
        
        for(int i = 1; i < n; i++){
            dp[i] = A[i] + (dp[i - 1] > 0 ? dp[i - 1] : 0);
            max = Math.max(max, dp[i]);
        }
        
        return max;
}
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 13,022评论 0 33
  • 33/16000, 28/35 忏悔贪占公产 今天下属乱停车贴条了,他说撕饭票多开一百报销实际上公司邑不允许的。我...
    南戴河西谜会馆慧慧阅读 176评论 0 0
  • 早上孩子起来晚了 和孩子商量了下以后的 生活准备怎么过 想叫孩子去参加期末考试 孩子说肯定考不好 怕有大的 失败的...
    苦茶_09e4阅读 187评论 0 0
  • 这一个月我经历了非常多又不算多的事儿,每天早上的篮球训练,每天下午的两小时阅读,还有每天早上下午的吉他课架子鼓课,...
    IversonKobe3824阅读 491评论 0 2

友情链接更多精彩内容