comments | difficulty | edit_url |
---|---|---|
true |
简单 |
给定一个整数数组(有正数有负数),找出总和最大的连续数列,并返回总和。
示例:
输入: [-2,1,-3,4,-1,2,1,-5,4] 输出: 6 解释: 连续子数组 [4,-1,2,1] 的和最大,为 6。
进阶:
如果你已经实现复杂度为 O(n) 的解法,尝试使用更为精妙的分治法求解。
我们定义
其中
答案为
时间复杂度
我们注意到
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
ans = f = -inf
for x in nums:
f = max(f, 0) + x
ans = max(ans, f)
return ans
class Solution {
public int maxSubArray(int[] nums) {
int ans = Integer.MIN_VALUE, f = Integer.MIN_VALUE;
for (int x : nums) {
f = Math.max(f, 0) + x;
ans = Math.max(ans, f);
}
return ans;
}
}
class Solution {
public:
int maxSubArray(vector<int>& nums) {
int ans = INT_MIN, f = INT_MIN;
for (int x : nums) {
f = max(f, 0) + x;
ans = max(ans, f);
}
return ans;
}
};
func maxSubArray(nums []int) int {
ans, f := math.MinInt32, math.MinInt32
for _, x := range nums {
f = max(f, 0) + x
ans = max(ans, f)
}
return ans
}
function maxSubArray(nums: number[]): number {
let [ans, f] = [-Infinity, -Infinity];
for (const x of nums) {
f = Math.max(f, 0) + x;
ans = Math.max(ans, f);
}
return ans;
}
/**
* @param {number[]} nums
* @return {number}
*/
var maxSubArray = function (nums) {
let [ans, f] = [-Infinity, -Infinity];
for (const x of nums) {
f = Math.max(f, 0) + x;
ans = Math.max(ans, f);
}
return ans;
};
class Solution {
func maxSubArray(_ nums: [Int]) -> Int {
var ans = Int.min
var f = Int.min
for x in nums {
f = max(f, 0) + x
ans = max(ans, f)
}
return ans
}
}