Maximum Subarray Leetcode Python
来源:互联网 发布:阿列克谢耶维奇 知乎 编辑:程序博客网 时间:2024/05/29 10:19
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],
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.
这题可以用三种方法来解。
第一种最容易想到的是 brute force的方法,把整个array循环两边。得到最大值。
这里空间O(1)
时间O(n^2)
def brutef(arr): maxval=-10000 for i in range(len(arr)): for j in range(i,len(arr)): if maxval<sum(arr[i:j]): print i,j maxval=max(maxval,sum(arr[i:j])) result=arr[i:j]
第二种借用mergesort的思想,将整个array依次往下分分别向左向右找最大,最后将最大的合并。
因为每次都要分两边,所以时间复杂度是O(nlog)
先定义一个函数是 dividecon 用来求每步最优
def dividecon(num,low,mid,high): #calculate left lowsum=-10000 cursum=num[low] left=low for index in reversed(range(low,mid)): cursum+=num[index] if cursum>lowsum: lowsum=cursum left=index highsum=-10000 cursum=0 right=high for index in range(mid+1,high): cursum+=num[index] if cursum>highsum: highsum=cursum right=index return [left,right,lowsum+highsum]再在 主函数里面调用这个函数。
def findsub(A,low,high): if high==low: return [low,high,A[low]] else: mid=low+(high-low)/2 [leftlow,lefthigh,leftsum]=findsub(A,low,mid) [rightlow,righthigh,rightsum]=findsub(A,mid+1,high) [crosslow,crosshigh,crosssum]=dividecon(A,low,mid,high)
if leftsum>=rightsum and leftsum>=crosssum: return [leftlow,lefthigh,leftsum]
if rightsum>=leftsum and rightsum>=crosssum: return [rightlow,righthigh,rightsum] else: return [crosslow,crosshigh,crosssum]依次比较如果最大都在左边,那就返回左边的值,如果最大都在右边那就返回右边的值,否则两者有交叉就返回cross的值
还要一种方法是时间O(n)空间 O(1)
做法就是把整个array扫描一遍记录下当前最大值,如果得到的当前值小于0就将其置0,最后可以得到答案
def findmax(arr): cursum=0 maxval=arr[0] for index in range(len(arr)): if cursum<0: cursum=0 cursum+=arr[index] maxval=max(maxval,cursum)
0 0
- leetcode:Maximum Subarray---python
- Maximum Subarray Leetcode Python
- Leetcode-Maximum Subarray-Python
- 【Leetcode】【python】Maximum Subarray
- 【LeetCode with Python】 Maximum Subarray
- Maximum Prodyct Subarray Leetcode Python
- [leetcode:python]53.Maximum Subarray
- [Leetcode]152. Maximum Product Subarray @python
- 【LeetCode】Maximum Subarray 和 Maximum Product Subarray
- LeetCode: Maximum Subarray
- LeetCode Maximum Subarray
- [Leetcode] Maximum Subarray
- LeetCode: Maximum Subarray
- leetcode 25: Maximum Subarray
- [LeetCode] Maximum Subarray
- [Leetcode] Maximum Subarray
- [LeetCode]Maximum Subarray
- [leetcode]Maximum Subarray
- 终端密码输入问题
- Iphone 6&6p,IOS8适配工作总结(2015-2-7更新)
- POJ 3785 The Next Permutation 全排列字典序法
- 2015—01—22 Shell学习笔记基础(1)
- Redis个人笔记
- Maximum Subarray Leetcode Python
- 第一篇 javase时钟表
- Hudson插件之按主题分类
- Oracle使用游标删除所有用户数据表中的所有记录脚本
- 安迪的第一个字典
- 黑马程序员Android第55期——tomcat与web程序结构与Http协议
- ORM framework源码分析:引言之Java JDBC
- MiniDLNA 1.1.4 添加对rmvb格式的支持
- Mybatis3源码分析(一):从sqlSession说起