Maximum Subarray - LeetCode
来源:互联网 发布:json字符串解析 编辑:程序博客网 时间:2024/06/05 18:39
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:
给一个我喜欢的AC方法:
If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.
要注意这里返回条件的界定和设定,十分容易出错!!!
这里的报错和我的Eclipse上显示的不一样,我认为我的方法应该是AC的, 不知道是什么bug。
Input:[-1,-2]Output:-2Expected:-1public class Solution { public int maxSubArray(int[] A) { int max = -9999; int maxindex = 0; int min = 9999; int minindex = 0; int sum = 0; int[] B = A; for(int i = 0; i < A.length; i++){ sum = sum + A[i]; B[i] = sum; //System.out.println(B[i]); } for(int i = 0; i < A.length; i++){ maxindex = (B[i] > max)? i:maxindex; max = Math.max(B[i], max); // System.out.println(maxindex); } for(int i = 0; i < A.length; i++){ minindex = (B[i] < min)? i:minindex; min = Math.min(B[i], min); } // System.out.println(maxindex); // System.out.println(minindex); if(maxindex == minindex) return A[maxindex]; else{ if(maxindex > minindex){ return B[maxindex] - B[minindex]; } else return - B[maxindex] + B[minindex]; } }}
给一个我喜欢的AC方法:
public class Solution {public int maxSubArray(int[] A) {int max = A[0];int[] sum = new int[A.length];sum[0] = A[0]; for (int i = 1; i < A.length; i++) {sum[i] = Math.max(A[i], sum[i - 1] + A[i]);max = Math.max(max, sum[i]);} return max;}}
0 0
- 【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
- Leetcode Maximum Subarray
- Populating Next Right Pointers in Each Node - LeetCode
- 【英语词组】attribute/ascribe/owe....to ....
- Single Number II - LeetCode
- 对网络的一些感悟
- ADB server didn't ACK
- Maximum Subarray - LeetCode
- Merge Sorted Array - LeetCode
- [LeetCode] Anagrams
- Reverse Nodes in k-Group -- LeetCode
- LeetCode Matrix Summary
- Linux文件系统预读(二)
- Add Two Numbers -- LeetCode
- Reverse linked list
- [LeetCode] Balanced Binary Tree