首页 > 其他分享 >leetcode 53. Maximum Subarray

leetcode 53. Maximum Subarray

时间:2023-05-30 17:34:54浏览次数:46  
标签:return nums int sum 53 ans Subarray leetcode dp

Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.

Example:

Input: [-2,1,-3,4,-1,2,1,-5,4],
Output: 6
Explanation: 
[4,-1,2,1] has the largest sum = 6.

Follow up:

If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.

贪心:

class Solution(object):
    def maxSubArray(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """

        ans = s = nums[0]
        for i in xrange(1, len(nums)):
            if s > 0:
                s = nums[i]+s                
            else:
                s = nums[i]
            ans = max(s, ans)
        return ans

DP解法://dp[i] means the maximum subarray ending with A[i];

class Solution(object):
    def maxSubArray(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        dp = [0]*len(nums)
        ans = dp[0] = nums[0]
        for i in xrange(1, len(nums)):
            dp[i] = max(dp[i-1]+nums[i], nums[i])
            ans = max(ans, dp[i])
        return ans

递归解法:

TODO

标签:return,nums,int,sum,53,ans,Subarray,leetcode,dp
From: https://blog.51cto.com/u_11908275/6381011

相关文章

  • leetcode 101. Symmetric Tree
    Givenabinarytree,checkwhetheritisamirrorofitself(ie,symmetricarounditscenter).Forexample,thisbinarytree[1,2,2,3,4,4,3]issymmetric:1/\22/\/\3443Butthefollowing[1,2,2,null,3,null,3]isnot:1/\2......
  • leetcode 191. Number of 1 Bits
    Writeafunctionthattakesanunsignedintegerandreturnsthenumberof’1'bitsithas(alsoknownastheHammingweight).Forexample,the32-bitinteger’11'hasbinaryrepresentation00000000000000000000000000001011,sothefunctionshould......
  • leetcode 326. Power of Three
    Givenaninteger,writeafunctiontodetermineifitisapowerofthree.Followup:Couldyoudoitwithoutusinganyloop/recursion?classSolution(object):defisPowerOfThree(self,n):""":typen:int......
  • leetcode 231. Power of Two
    Givenaninteger,writeafunctiontodetermineifitisapoweroftwo.classSolution(object):defisPowerOfTwo(self,n):""":typen:int:rtype:bool"""#-4???ifn>......
  • leetcode 27. Remove Element
    Givenanarraynumsandavalueval,removeallinstancesofthatvaluein-placeandreturnthenewlength.Donotallocateextraspaceforanotherarray,youmustdothisbymodifyingtheinputarrayin-placeTheorderofelementscanbechanged.Itdoesn&......
  • leetcode 594. Longest Harmonious Subsequence
    Wedefineaharmoniousarrayisanarraywherethedifferencebetweenitsmaximumvalueanditsminimumvalueisexactly1.Now,givenanintegerarray,youneedtofindthelengthofitslongestharmonioussubsequenceamongallitspossiblesubsequences.E......
  • leetcode 836. Rectangle Overlap
    Arectangleis representedasa list[x1,y1,x2,y2],where (x1,y1) arethecoordinatesofitsbottom-leftcorner,and(x2, y2) arethecoordinatesofitstop-rightcorner.Tworectanglesoverlapiftheareaoftheirintersectionispositive. Tobecl......
  • leetcode 342. Power of Four
    Givenaninteger(signed32bits),writeafunctiontocheckwhetheritisapowerof4.Example:Givennum=16,returntrue.Givennum=5,returnfalse.Followup:Couldyousolveitwithoutloops/recursion?解法1,经典的数学解法:classSolution(object):def......
  • leetcode 345. Reverse Vowels of a String
    Writeafunctionthattakesastringasinputandreverseonlythevowelsofastring.Example1:Givens="hello",return"holle".Example2:Givens="leetcode",return"leotcede".Note:Thevowelsdoesnotincl......
  • leetcode Most Common Word——就是在考察自己实现split
    819.MostCommonWordGivenaparagraph andalistofbannedwords,returnthemostfrequentwordthatisnotinthelistofbannedwords. Itisguaranteedthereisatleastonewordthatisn'tbanned,andthattheanswerisunique.Wordsinthelist......