Maximum Subarray (JAVA)
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
.
1 public static int maxSubArray(int[] A) 2 { 3 int max=A[0]; 4 for(int i=0;i<A.length;i++) 5 { 6 int sum=0; 7 for(int j=i;j<A.length;j++) 8 { 9 sum+=A[j]; 10 if(sum>max)12 max=sum;15 } 16 } 17 18 return max; 19 }
O(n):
public static int maxSubArray(int[] A) { int max=A[0]; int sum=0; for(int i=0;i<A.length;i++) { sum+=A[i]; if(sum>max) max=sum; if(sum<0) sum=0; } return max; }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。