Brute Force
Intuition
The simplest approach is to consider every possible subarray, compute its sum, and track the maximum. We use two nested loops to define the start and end of each subarray, and a running sum to efficiently compute each subarray's total. This guarantees we check all candidates but is slow for large inputs.
Algorithm
- Initialize maxSum to the smallest possible integer value.
- For each starting index i from 0 to n-1, initialize a running currentSum to 0.
- For each ending index j from i to n-1, add nums[j] to currentSum.
- Update maxSum if currentSum is greater than maxSum.
- Return maxSum after all subarrays have been checked.
O(n^2)SpaceO(1)Code (C++ · Java · Python · Go)
class Solution {
public:
int maxSubArray(vector<int>& nums) {
int maxSum = INT_MIN;
for (int i = 0; i < nums.size(); i++) {
int currentSum = 0;
for (int j = i; j < nums.size(); j++) {
currentSum += nums[j];
maxSum = max(maxSum, currentSum);
}
}
return maxSum;
}
};class Solution {
public int maxSubArray(int[] nums) {
int maxSum = Integer.MIN_VALUE;
for (int i = 0; i < nums.length; i++) {
int currentSum = 0;
for (int j = i; j < nums.length; j++) {
currentSum += nums[j];
maxSum = Math.max(maxSum, currentSum);
}
}
return maxSum;
}
}def maxSubArray(nums: list[int]) -> int:
max_sum = float('-inf')
for i in range(len(nums)):
current_sum = 0
for j in range(i, len(nums)):
current_sum += nums[j]
max_sum = max(max_sum, current_sum)
return max_sumfunc maxSubArray(nums []int) int {
maxSum := nums[0]
for i := 0; i < len(nums); i++ {
currentSum := 0
for j := i; j < len(nums); j++ {
currentSum += nums[j]
if currentSum > maxSum {
maxSum = currentSum
}
}
}
return maxSum
}