Continuous Subarray Sum (Return index)

这道题实际上就是subarray系列题目最基本的一道题目稍作改变的变体,思路上基本是一模一样的,即用一个临时变量累加当前的值,当累加值还不如当前值本身大时,放弃此累加值而把累加值改成当前值继续往前遍历,这个思维本质上是有点类似动态规划的,在这道题里还有一个额外的地方就是题目要求返回下标,则还需要一个cum变量记录当前结果的累加最大值,另外还需要一个start变量来记录累加值不如当前值大时的一个起点坐标,代码如下

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, nums):
        # Write your code here
        res = [0, 0]
        cum = -sys.maxint                       # 最大结果值
        tmp = 0                                 # 遍历时的累加变量
        start = 0                               # 最大子数组的起始坐标
        n = len(nums)

        for i in xrange(n):
            tmp += nums[i]                    
            if tmp < nums[i]:                   # 当前值更大时起始坐标要更新
                tmp = nums[i]
                start = i
            if tmp > cum:                       # 每步都需要检查一下累加值是不是比当前的最大结果值还要大
                cum = tmp
                res = [start, i]

        return res

results matching ""

    No results matching ""