zoukankan      html  css  js  c++  java
  • Python3解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.

    思路:
    动态规划问题,从头开始遍历数组,每次都考虑以 当前索引为结束位置 的所有数组求和的最大值,依次类推,从而依次得到以 每一个索引为结束位置的 相应所有数组求和最大值,进而形成一个列表,取该列表最大值即可
    class Solution:
        def maxSubArray(self, nums: List[int]) -> int:
            dp = [0 for i in (range(len(nums)+1))]
            dp[0] = float("-inf")
            for i in range(1,len(nums)+1):
                dp[i] = max(dp[i-1]+nums[i-1],nums[i-1])
            return max(dp)


  • 相关阅读:
    mac下配置openCV
    K最短路 A*算法
    KMP算法
    北航复试机试题
    1385重建二叉树
    二维数组中的查找
    简单的单向链表
    Getting Started with WebRTC [note]
    我的c漏洞
    PeerConnection
  • 原文地址:https://www.cnblogs.com/xiaohua92/p/11064164.html
Copyright © 2011-2022 走看看