comments | difficulty | edit_url |
---|---|---|
true |
Easy |
You are given an array of integers (both positive and negative). Find the contiguous sequence with the largest sum. Return the sum.
Example:
Input: [-2,1,-3,4,-1,2,1,-5,4] Output: 6 Explanation: [4,-1,2,1] has the largest sum 6.
Follow Up:
If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.
We define
where
The answer is
The time complexity is
We notice that
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
}
}