一、题目
Find the contiguous subarray within an array (containing at least one number) which has the largest sum.
For example, given the array [-2,1,-3,4,-1,2,1,-5,4]
,
the contiguous subarray [4,-1,2,1]
has the largest sum = 6
.
题目是说,给你一串数,有正有负 要求出最大的连续子串
二、解题思路
目前感觉自身还是硬编码,还没有建立算法思想,拿到题首先想到的还是逐个遍历,内层再定义一个变量 j ,记录当前元素 i ,所能组合的符合条件的最大长度,题目并没有要求输出最大数的子串,但为了锻炼下,我用了一个字典来存储当前元素的符合条件的最大子串和值。整个算法的复杂度我感觉差不多到O(n*n)了,提交上去之后,系统显示超时了。搜了搜网上的做法,发现自己的太low了,这道题大家普遍用的是动态规划的思想,基本思路:在每一步我们都需要维护两个变量,一个是全局最优,就是到当前元素为止的最优的解;一个是局部最优解,就是必须包含当前元素的最优解。其复杂度应该是O(n),只需要遍历一次数组即可。
#coding:utf-8 import time def maxSubArray1(nums): """ :type nums: List[int] :rtype: int """ maxnums = -float('inf') dict = {} for i in range(len(nums)): j = i + 1 while j <= len(nums): b = [nums[j] for j in range(i,j)] if sum(b) > maxnums: maxnums = sum(b) dict.update({maxnums:nums[i:j:1]}) #print(dict) j+=1 print(maxnums) print("the biggest nums's is",dict[maxnums]) return maxnums,dict[maxnums] def maxSubArray2(nums): thissum = 0 maxsum = -float('inf') for i in range(len(nums)): if thissum < 0: thissum = 0 #归零表示当前的sum为负,越加越小,这里thissum = 0表示当前的num[i] thissum += nums[i] maxsum = max(maxsum, thissum) #全局最大值 print(maxsum) return maxsum def maxSubArray3(nums): l = g = -float('inf') #这里应该初始化为无穷小 for n in nums: l = max(n, l + n) #l中存的是局部最大值 g = max(l, g) #g中存在的是全局最大值 print(g) return g if __name__ == '__main__': a = [-2,1,-3,4,-1,2,1,-5,4] starttime1 = time.clock() maxSubArray1(a) endtime1 = time.clock() print("maxSubArray1 cost time is %d."%(endtime1 - starttime1)) starttime2 = time.time() maxSubArray2(a) endtime2 = time.time() print("maxSubArray2 cost time is %d." % (endtime2 - starttime2)) maxSubArray3(a) starttime3 = time.time() endtime3 = time.time() print("maxSubArray3 cost time is %d." % (endtime3 - starttime3))
博客参考:https://blog.csdn.net/linhuanmars/article/details/21314059
https://www.cnblogs.com/xbf9xbf/p/4240510.html