Tutorialspoint
Problem
Solution
Submissions

Maximum Subarray

Certification: Basic Level Accuracy: 100% Submissions: 10 Points: 5

Write a Java program to find the contiguous subarray which has the largest sum and return its sum using Kadane's Algorithm.

Example 1
  • Input: nums = [-2, 1, -3, 4, -1, 2, 1, -5, 4]
  • Output: 6
  • Explanation:
    • Subarray [4, -1, 2, 1] has the maximum sum
Example 2
  • Input: nums = [1]
  • Output: 1
  • Explanation:
    • Only one element — that is the maximum
Constraints
  • 1 ≤ nums.length ≤ 10^5
  • -10^4 ≤ nums[i] ≤ 10^4
  • Time Complexity: O(n)
  • Space Complexity: O(1)
ArraysTech MahindraPwC
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use Kadane's algorithm to solve this efficiently
  • Keep track of the current sum and the maximum sum found so far
  • If the current sum becomes negative, reset it to zero
  • Consider the edge case of all negative numbers
  • Iterate through the array only once

Steps to solve by this approach:

 Step 1: Initialize variables currentSum and maxSum with the first element of the array.
 Step 2: Iterate through the array starting from the second element.
 Step 3: For each element, decide whether to start a new subarray or continue the previous one.
 Step 4: Update maxSum if the new currentSum is greater than the existing maxSum.
 Step 5: Return maxSum at the end of the iteration.
 Step 6: Handle edge cases like empty array or single element array.
 Step 7: The solution has O(n) time complexity and O(1) space complexity.

Submitted Code :