Tutorialspoint
Problem
Solution
Submissions

Maximum Subarray

Certification: Basic Level Accuracy: 0% Submissions: 0 Points: 5

Write a C program to find the contiguous subarray within an array of integers which has the largest sum. This is a classic problem that can be efficiently solved using Kadane's Algorithm. The algorithm finds the maximum sum of a contiguous subarray in a one-dimensional array of numbers.

Example 1
  • Input: nums = [-2, 1, -3, 4, -1, 2, 1, -5, 4]
  • Output: 6
  • Explanation: The subarray [4, -1, 2, 1] has the largest sum = 6.
Example 2
  • Input: nums = [5, 4, -1, 7, 8]
  • Output: 23
  • Explanation: The entire array [5, 4, -1, 7, 8] forms the subarray with the largest sum = 23.
Constraints
  • 1 ≤ nums.length ≤ 10^5
  • -10^4 ≤ nums[i] ≤ 10^4
  • Time Complexity: O(n)
  • Space Complexity: O(1)
ArraysAlgorithmsCapgeminiD. E. Shaw
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 problem
  • Maintain two variables: current_sum and max_sum
  • For each element, decide whether to include it in the current subarray or start a new subarray
  • If the current element is greater than the current sum plus the element, start a new subarray
  • Update the maximum sum found so far by comparing it with the current sum

Steps to solve by this approach:

 Step 1: Initialize variables current_sum = 0 and max_sum = INT_MIN.

 Step 2: Iterate through each element in the array.
 Step 3: For each element, decide whether to start a new subarray or extend the existing one.
 Step 4: Update current_sum to the maximum of these two values.
 Step 5: Update max_sum if current_sum is greater.
 Step 6: Continue this process for all elements in the array.
 Step 7: Return max_sum as the result, which represents the maximum subarray sum.

Submitted Code :