LeetCode简单题:53. 最大子序和(Python,C++,Java)

一.解法

https://leetcode-cn.com/problems/maximum-subarray/
要点:dp动态规划
注意转移方程为v[i] = max(v[i-1]+nums[i],nums[i]),v[i]表示结尾为位置i且子串包含了nums[i]的最大字序和的子串
Python,C++,Java都用了同样的dp算法,最后比较所有结尾位置为i的最大子序和的最大值即可

二.Python实现

class Solution:
    def maxSubArray(self, nums: List[int]) -> int:
        if len(nums)==0:
            return 0
    
        answer=[]
        finalanswer=nums[0];
        answer.append(nums[0])
        
        i=1
        while i<=len(nums)-1:
            temp=max(answer[i-1]+nums[i],nums[i])
            answer.append(temp)
            if temp>finalanswer:
                finalanswer=temp
            i+=1
        
        return finalanswer

三.C++实现

class Solution {
public:
    int maxSubArray(vector& nums) {
        //dp
        //1.状态定义 F(i)表示下标为i时连续数组的最大和
        //2.状态转移方程 F(i) = max(F(i-1)+nums[i],nums[i]);
        //3.初始状态 F(0) = nums[0];
        //4.返回值 F(nums.size()-1)
        
        //code
        if(nums.empty()) return 0;
        
        vector v(nums);
        v[0]=nums[0];
        int maxNum = nums[0];
        for(int i = 1;i < nums.size();++i){
            v[i] = max(v[i-1]+nums[i],nums[i]);
            
            if(maxNum < v[i])
                maxNum = v[i];
        }
        
        return maxNum;
    }
};

四.java实现

class Solution {
    public int maxSubArray(int[] nums) {

        if(nums.length==0) return 0;
        int[] answer = new int[nums.length];
        answer[0] = nums[0];
      
        int maxNum = nums[0];
        for(int i = 1;i < nums.length;++i){
            answer[i] = Math.max(answer[i-1]+nums[i],nums[i]);
            
            if(maxNum < answer[i])
                maxNum = answer[i];
        }
        
        return maxNum;
        

    }
}

你可能感兴趣的:(LeetCode简单题:53. 最大子序和(Python,C++,Java))