算法系列——Maximum Subarray

来源:互联网 发布:bt种子在线播放软件 编辑:程序博客网 时间:2024/06/03 21:30

题目描述

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.

解题思路

题目要求是让我们实现一个算法,求连续字数组的最大值。
基本思路是这样的,在每一步,我们维护两个变量,一个是全局最优,就是到当前元素为止最优的解是,一个是局部最优,就是必须包含当前元素的最优的解。
时间复杂度为O(n)

程序实现

public class Solution {    public int maxSubArray(int[] nums) {        int maxSum=Integer.MIN_VALUE;        int curMaxSum=0;        for(int num:nums){            curMaxSum=Math.max(curMaxSum+num,num);            maxSum=Math.max(maxSum,curMaxSum);        }        return maxSum;    }}
原创粉丝点击