#include <limits.h>
int maxSubArray(int *nums, int numsSize) {
int sum = 0;
int mx = INT_MIN;
for (int i = 0; i < numsSize; i++) {
sum += nums[i];
if (sum > mx)
mx = sum;
if (sum < 0)
sum = 0; // a negative prefix only lowers what follows
}
return mx;
}
#include <algorithm>
#include <climits>
#include <vector>
using namespace std;
class Solution {
public:
int maxSubArray(vector<int> &nums) {
int sum = 0;
int mx = INT_MIN;
for (int i = 0; i < nums.size(); i++) {
sum += nums[i];
mx = max(sum, mx);
if (sum < 0)
sum = 0; // a negative prefix only lowers what follows
}
return mx;
}
};
package greedy
import "math"
func maxSubArray(nums []int) int {
sum := 0
mx := math.MinInt
for _, n := range nums {
sum += n
mx = max(sum, mx)
if sum < 0 {
sum = 0 // a negative prefix only lowers what follows
}
}
return mx
}
class Solution {
public int maxSubArray(int[] nums) {
int sum = 0;
int mx = Integer.MIN_VALUE;
for (int n : nums) {
sum += n;
mx = Math.max(sum, mx);
if (sum < 0)
sum = 0; // a negative prefix only lowers what follows
}
return mx;
}
}
/**
* @param {number[]} nums
* @return {number}
*/
var maxSubArray = function (nums) {
let sum = 0;
let mx = -Infinity;
for (const n of nums) {
sum += n;
mx = Math.max(sum, mx);
if (sum < 0) sum = 0; // a negative prefix only lowers what follows
}
return mx;
};
from typing import List
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
total = 0
mx = float("-inf")
for n in nums:
total += n
mx = max(total, mx)
if total < 0:
total = 0 # a negative prefix only lowers what follows
return mx
impl Solution {
pub fn max_sub_array(nums: Vec<i32>) -> i32 {
let mut sum = 0;
let mut mx = i32::MIN;
for n in nums {
sum += n;
mx = mx.max(sum);
if sum < 0 {
sum = 0; // a negative prefix only lowers what follows
}
}
mx
}
}