Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
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.
Example 2:
Input: nums = [1]
Output: 1
Example 3:
Input: nums = [0]
Output: 0
Example 4:
Input: nums = [-1]
Output: -1
Example 5:
Input: nums = [-100000]
Output: -100000
Constraints:
1 <= nums.length <= 3 * 104
-105 <= nums[i] <= 105
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.
Solution:
Approach 1: Brute Force O(n^2)
class Solution {
public int maxSubArray(int[] nums) {
int max=Integer.MIN_VALUE;
for(int i=0; i<nums.length;i++)
{
int sum=0;
for(int j=i;j<nums.length;j++)
{
sum+=nums[j];
max=Math.max(max,sum);
}
}
return max;
}
}
Approach 2: Kadane's Algorithm O(n)
class Solution {
public int maxSubArray(int[] nums) {
int sum=nums[0];
int output=nums[0];
for(int i=1; i<nums.length;i++)
{
sum=Math.max(nums[i],sum+nums[i]);
output=Math.max(output,sum);
}
return output;
}
}
Comments