13.2 Maximum Subarray
来源:互联网 发布:淘宝重复铺货怎么处罚 编辑:程序博客网 时间:2024/06/08 19:37
Link: https://oj.leetcode.com/problems/maximum-subarray/
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
Approach I:Kadane's Algorithm
Time: O(n), Space: O(1)
Note: By initializing local and global to A[0], not 0, we can deal with the scenario when A has all negative elements.
http://blog.csdn.net/linhuanmars/article/details/21314059
public class Solution { public int maxSubArray(int[] A) { int local = A[0];//Initialized to A[0], not 0 int global = A[0];//Initialized to A[0], not 0 for(int i = 1; i < A.length; i++){ local = Math.max(A[i], local+A[i]); global = Math.max(global, local); } return global; }}
Approach II: Divide and Conquer //don't understand (can't draw flow)
Time: O(nlogn),
public class Solution { public int maxSubArray(int[] A) { //my 2nd attempt for the 2nd solution: divide-and-conquer after seeing the answer int left = 0; int right = A.length - 1; int max = Integer.MIN_VALUE; return maxSubArray(A, left, right, max); } public int maxSubArray(int[] A, int left, int right, int max) { if(left > right){ return Integer.MIN_VALUE; } int mid = (left + right)/2; int leftMax = maxSubArray(A, left, mid-1, max); max = Math.max(max, leftMax); int rightMax = maxSubArray(A, mid+1, right, max); max = Math.max(max, rightMax); //if the maxSubArray goes across the mid int lSum = 0; int maxLSum = 0; for(int i = mid-1; i>=left;i-- ){ lSum += A[i]; if(lSum > maxLSum){ maxLSum = lSum; } } int rSum = 0; int maxRSum = 0; for(int i = mid+1; i<=right;i++){ rSum += A[i]; if(rSum > maxRSum){ maxRSum = rSum; } } return Math.max(max, maxLSum+maxRSum+A[mid]); }}
相关题目:Jump Game (Approach I)
0 0
- 13.2 Maximum Subarray
- maximum subarray
- Maximum Subarray
- Maximum Subarray
- Maximum Subarray
- Maximum Subarray
- Maximum Subarray
- Maximum Subarray
- Maximum Subarray
- Maximum Subarray
- Maximum Subarray
- Maximum Subarray
- Maximum Subarray
- Maximum Subarray
- Maximum Subarray
- Maximum Subarray
- Maximum Subarray
- Maximum Subarray
- java基本数据类型
- gcc编译器的使用
- robotium测试工具使用之——输出log日志
- SQL Server:命名规则
- Cg学习笔记(一)
- 13.2 Maximum Subarray
- Git超简单入门简明教程--写给一直不敢用Git的同学
- Oracle10g和11g在新增表字段时default的性能影响
- 嵌入式linux面试题
- Qt程序打包成exe可执行文件图文教程
- nagios 客户端扩展脚本检测批量url web 状态
- iOS 数据库 sql语句 存放对象
- 边缘检测之LOG算子
- 类型转换