博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode - Maximum Subarray
阅读量:7082 次
发布时间:2019-06-28

本文共 1324 字,大约阅读时间需要 4 分钟。

Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.Example:Input: [-2,1,-3,4,-1,2,1,-5,4],Output: 6Explanation: [4,-1,2,1] has the largest sum = 6.

algorithm that operates on arrays: it starts at the left end (element A[1]) and scans through to the right end (element A[n]), keeping track of the maximum sum subvector seen so far. The maximum is initially A[0]. Suppose we've solved the problem for A[1 .. i - 1]; how can we extend that to A[1 .. i]? The maximum

sum in the first I elements is either the maximum sum in the first i - 1 elements (which we'll call MaxSoFar), or it is that of a subvector that ends in position i (which we'll call MaxEndingHere).

 

MaxEndingHere is either A[i] plus the previous MaxEndingHere, or just A[i], whichever is larger.

class Solution {    public int maxSubArray(int[] nums) {        if(nums == null || nums.length == 0){            return 0;        }        int maxSoFar = nums[0];        int maxEndingHere = nums[0];        for(int i = 1; i < nums.length; i++){            maxEndingHere = Math.max(maxEndingHere + nums[i], nums[i]);            maxSoFar = Math.max(maxSoFar, maxEndingHere);        }        return maxSoFar;    }    }

  

转载于:https://www.cnblogs.com/incrediblechangshuo/p/10052469.html

你可能感兴趣的文章
日志可视化分析
查看>>
没有vcenter的克隆vm的方法(ESXi5 youtube)
查看>>
docker深入2-容器删除操作失败
查看>>
htmlspecialchars
查看>>
解决Ubuntu下sqldeveloper中文乱码问题
查看>>
常见Linux系统目录、文件类型、ls命令、alias命令
查看>>
试用时间序列数据库InfluxDB
查看>>
mongodb的备份(mongodump)与恢复(mongorestore)
查看>>
第二节 MySQL增加新用户
查看>>
OKhttp3中的cookies
查看>>
客户端TortoiseSVN的安装及使用方法
查看>>
解决jsp访问jsp与Servlet访问jsp路径存在的差异性比较
查看>>
ACM,坚持到底!!!!
查看>>
数整型值数组求长度sizeof(a)/sizeof(int);
查看>>
泛型KMP算法
查看>>
XMLHttpRequest(ajax)跨域请求的优雅方法:CORS
查看>>
jQuery 练习[二]: 获取对象(3) - 根据属性、内容匹配, 还有表单元素匹配
查看>>
再学 GDI+[88]: TGPImage(8) - 放大镜
查看>>
mysql数据库同步详解
查看>>
JSON 之 SuperObject(5): Format 与转义字符
查看>>