LeetCode 100 Maximum Subarray
来源:互联网 发布:vm虚拟机没有网络 编辑:程序博客网 时间:2024/05/16 04:25
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.
click to show more practice.
More practice:
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.
click to show more practice.
More practice:
If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.
分析:
因为这里不要求返回数组下标,可以通过一趟遍历来把所有元素相加,当和小于0的时候,舍弃之前所有。
这里是一个O(n)的解法。
public class Solution { public int maxSubArray(int[] A) { int sum = 0; int maxSum = Integer.MIN_VALUE; for(int i=0; i<A.length; i++){ sum += A[i]; maxSum = Math.max(maxSum, sum); if(sum < 0) sum=0; } return maxSum; }}
0 0
- LeetCode 100 Maximum Subarray
- 【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
- LeetCode-Maximum Subarray
- [leetcode] Maximum Subarray
- LeetCode 45: Maximum Subarray
- LeetCode - Maximum Subarray
- LeetCode:Maximum Subarray
- LeetCode 53: Maximum Subarray
- 【leetcode】Maximum Subarray
- win7(32/64)+apache2.4+php5.5+mysql5.6 环境搭建配置
- IOS 后台定位并向服务器发送当前位置
- ArcGIS API for Flex(六)加载自定义Web平铺图层
- 第一篇文章,献给自己最近在读的一首诗---《人的一生》
- sdfdsf
- LeetCode 100 Maximum Subarray
- Linux 设备驱动 一
- 架构师趣味回答 java
- CSDN博客导出(二) - 解析HTML
- Android中利用Handler实现消息的分发机制(二)
- Leetcode - 广度优先遍历
- nginx 常用配置
- Linux中iptables设置详细
- Objective-C 内存管理