zoukankan      html  css  js  c++  java
  • 【LeetCode每天一题】Maximum Subarray(最大子数组)

    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.

    思路


          这道题看到之后第一想到的就是使用动态规划来解决这个问题。使用动态规划需要申请一个辅助数组,另外还需要动态方程,方程为dp[i] = nums[i] + ( dp[i-1] if dp[i-1] > 0 else 0)。 这种解法的时间复杂度为O(n),空间复杂度为O(n)。

      第二种思路就是我们设置一个sum_标志量和结果变量,然后从头遍历,使用sum_变量存储连续数组的和,如果当前小于0直接赋值为0。最后返回结果变量。时间复杂度为O(n),空间复杂度为O(1)。

    第一种思路代码


     1 class Solution(object):
     2     def maxSubArray(self, nums):
     3         """
     4         :type nums: List[int]
     5         :rtype: int
     6         """
     7         if len(nums) < 1 :
     8             return  0
     9         dp = [0] * len(nums)     # 辅助数组
    10         dp[0] = nums[0]    # 记录nums第一个的值
    11         max_num = dp[0]     # 记录子数组最大的值
    12         for i in range(1, len(nums)):
    13             dp[i] = nums[i] + (dp[i-1] if dp[i-1]> 0 else 0)   # 记录当前最大的子数组和的值
    14             max_num = max(max_num, dp[i])      
    15         return max_num

    第二种思路解决办法


     1 class Solution(object):
     2     def maxSubArray(self, nums):
     3         """
     4         :type nums: List[int]
     5         :rtype: int
     6         """
     7         if len(nums) < 1 :
     8             return  0
     9         res, sum_ = nums[0], 0
    10         for i in nums:       
    11             sum_ += i       
    12             res = max(sum_, res)
    13             if sum_ < 0:
    14                 sum_ = 0
    15         return res
  • 相关阅读:
    调研一类软件的发展演变—聊天软件( 1000-2000 words, in Chinese)
    C++用法的学习心得(要求包含示例,并反映出利用网络获取帮助的过程)
    软件工程学习总结
    南通大学教务管理微信公众号体验
    设计一款给爸爸妈妈用的手机
    第二次作业
    web browser 发展史
    c++用法的学习心得
    电梯调度
    一个数组既有正数也有负数,计算出它的子数组和的最大值。
  • 原文地址:https://www.cnblogs.com/GoodRnne/p/10726043.html
Copyright © 2011-2022 走看看