LintCode: 连续子数组求和

LintCode: 连续子数组求和

需要考虑很多种情况,也是看了数据才知道逻辑哪里不对,感觉自己考虑问题很不全面。

import copy
class Solution:
    # @param {int[]} A an integer array
    # @return {int[]}  A list of integers includes the index of the 
    #                  first number and the index of the last number
    def continuousSubarraySum(self, A):
        # Write your code here
        if not A:
            return
        n = len(A)
        dp = [0 for i in range(n)]
        dp[0] = A[0]
        ans = [0, 0]
        max_tmp = A[0]
        tmp = 0
        for i in range(1, n):
            dp[i] = max(dp[i-1] + A[i], A[i])
            if dp[i] >= max_tmp:
                if dp[i] == dp[i-1] + A[i]:
                    max_tmp = dp[i]
                    ans[1] = i
                    tmp = ans[0]
            if dp[i-1] < 0 and (dp[i] > 0 or dp[i-1] < dp[i]):
                ans[0] = i
                if dp[i] > max_tmp:
                    ans[1] = i
        if ans[0] > ans[1]:
            ans = [tmp, ans[1]]
        return ans

你可能感兴趣的:(lintcode,python)