【题目描述】
数组
Given an array of integers, find a contiguous subarray which has the largest sum.
app
Notice:The subarray should contain at least one number.ide
给定一个整数数组,找到一个具备最大和的子数组,返回其最大和。
spa
注意:子数组最少包含一个数code
【题目连接】orm
http://www.lintcode.com/en/problem/maximum-subarray/
get
【题目解析】it
O(n)就是一维DP.
io
假设A(0, i)区间存在k,使得[k, i]区间是以i结尾区间的最大值, 定义为Max[i], 在这里,当求取Max[i+1]时,ast
Max[i+1] = Max[i] + A[i+1], if (Max[i] + A[i+1] >0)
= 0, if(Max[i]+A[i+1] <0),若是和小于零,A[i+1]必为负数,不必保留,舍弃掉
而后从左往右扫描,求取Max数字的最大值即为所求。
【参考答案】