LeetCode:53. Maximum Subarray

 1 package day20170206;
 2 //LeetCode:53. Maximum Subarray
 3 /*
 4  Find the contiguous subarray within an array (containing at least one number) which has the largest sum.
 5 
 6 For example, given the array [-2,1,-3,4,-1,2,1,-5,4],
 7 the contiguous subarray [4,-1,2,1] has the largest sum = 6.
 8 
 9 click to show more practice.
10 
11 More practice:
12 If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.
13  */
14 public class maxSubArray53 {
15     public static int maxSubArray(int[] nums) {
16         int max=nums[0];
17         for(int i=0;i<nums.length;i++){
18             for(int j=i,sum=0;j<nums.length;j++){
19                 sum+=nums[j];
20                 if(sum>max)
21                     max=sum;
22             }
23         }
24         return max;
25     }
26     //study if(AB+C)<C,AB<0,且A<AB
27     public static int maxSubArray2(int[] nums){
28         int max=nums[0],subMax=nums[0];
29         for(int i=1;i<nums.length;i++){
30             subMax=Math.max(nums[i]+subMax, nums[i]);
31             max=Math.max(max, subMax);
32         }
33         return max;
34     }
35     public static void main(String[] args) {
36         // TODO Auto-generated method stub
37         int[] nums={-2,1,-3,4,-1,2,1,-5,4};
38         int[] nums2={-2,1};
39         int[] nums3={1};
40         
41         System.out.println(maxSubArray(nums));
42         System.out.println(maxSubArray(nums2));
43         System.out.println(maxSubArray(nums3));
44         
45         System.out.println(maxSubArray2(nums));
46         System.out.println(maxSubArray2(nums2));
47         System.out.println(maxSubArray2(nums3));
48     }
49 
50 }

 

转载于:https://www.cnblogs.com/luluqiao/p/6372746.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值