LeetCode53. Maximum Subarray

来源:互联网 发布:怪物猎人p3雷狼数据 编辑:程序博客网 时间:2024/05/21 21:46

53.Maximum Subarray
题意:在一个给定数组中找一个和最大的子数组(至少含有一个元素)。
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、如果加上当前位的和<当前位的值,则舍弃前面的计算结果,直接让sum=当前值,这个sum就是currentSum;
2、设置两个sum,一个是currentSum,用来记录遍历数组过程中的最大和,另一个是maxSum,用来记录历史的currentSum,然后与当前的currentSum相比较,较大值即为maxSum,即maxSum = Math.max(currentSum, maxSum);

public int maxSubArray(int[] nums) {    int currentSum = nums[0];    int maxSum = currentSum;        for(int i = 1; i < nums.length; i++){                currentSum +=nums[i];            if(currentSum < nums[i]){                currentSum = nums[i];            }            maxSum = Math.max(currentSum, maxSum);        }        return maxSum;    }

另一种方法:思路一样,但是写法更加简洁。

public static int maxSubArray1(int[] A) {        int maxSoFar=A[0], maxEndingHere=A[0];        for (int i=1;i<A.length;++i){            maxEndingHere= Math.max(maxEndingHere+A[i],A[i]);            maxSoFar=Math.max(maxSoFar, maxEndingHere);         }        return maxSoFar;    }
原创粉丝点击