https://github.com/emahtab/maximum-subarray-sum
Find the maximum contiguous subarray sum
https://github.com/emahtab/maximum-subarray-sum
kadane-algorithm leetcode problem-solving
Last synced: 5 months ago
JSON representation
Find the maximum contiguous subarray sum
- Host: GitHub
- URL: https://github.com/emahtab/maximum-subarray-sum
- Owner: eMahtab
- Created: 2019-11-27T17:24:43.000Z (over 6 years ago)
- Default Branch: master
- Last Pushed: 2022-04-15T11:11:48.000Z (almost 4 years ago)
- Last Synced: 2025-10-14T01:04:24.163Z (5 months ago)
- Topics: kadane-algorithm, leetcode, problem-solving
- Language: Java
- Homepage:
- Size: 11.7 KB
- Stars: 2
- Watchers: 1
- Forks: 1
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# Maximum Contiguous Subarray Sum (Kadane's Algorithm)
## https://leetcode.com/problems/maximum-subarray
Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
A subarray is a contiguous part of an array.
```
Example 1:
Input: nums = [-2,1,-3,4,-1,2,1,-5,4]
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.
```
For array [-2, 1, -3, 4, -1, 2, 1, -5, 4] the maximum contiguous subarray sum is 6 [4, -1, 2, 1]
**More examples :**
```
[-1, 1] => Max Contiguous Subarray sum is 1
[-1, 1, 2, -1, 2] => Max Contiguous Subarray sum is 4 [1, 2, -1, 2]
```
## This is a beautiful question 😲
We can use the Kadane's algorithm to find the maximum contiguous subarray sum in just one iteration through the input array.
```java
class Solution {
public int maxSubArray(int[] nums) {
if(nums == null || nums.length == 0)
return 0;
int maxSum = nums[0];
int currentMax = nums[0];
for(int i = 1; i < nums.length; i++){
currentMax = Math.max(nums[i], nums[i]+currentMax);
maxSum = Math.max(maxSum, currentMax);
}
return maxSum;
}
}
```
```
Runtime Complexity : O(n)
Space Complexity : O(1)
```