Maximum Subarray Solution for Capgemini

Company: Capgemini · Difficulty: Hard · Topics: Array, Dynamic Programming, Divide and Conquer

Problem Statement

Given an integer array nums, find the subarray with the largest sum, and return its sum.

A subarray is a contiguous part of an array.

Examples

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 = [1]

Output: 1

Explanation: The subarray [1] has the largest sum 1.

Example 3:

Input: nums = [5,4,-1,7,8]

Output: 23

Explanation: The subarray [5,4,-1,7,8] has the largest sum 23.

Example 4:

Input: nums = [-1,-2,-3,-4]

Output: -1

Explanation: The subarray [-1] has the largest sum -1.

Intuition

The key insight is that we can solve this problem using Kadane's algorithm, which keeps track of the maximum sum ending at each position. If the current sum becomes negative, we reset it to the current element.

Approach

Approach 1: Kadane's Algorithm (Optimal)

1. Initialize maxSum and currentSum to the first element

2. For each element starting from the second:

3. Return maxSum

Approach 2: Dynamic Programming

1. Create a DP array where dp[i] represents max sum ending at index i

2. dp[i] = max(nums[i], dp[i-1] + nums[i])

3. Find maximum value in DP array

Approach 3: Brute Force

1. Check all possible subarrays

2. Calculate sum for each subarray

3. Keep track of maximum sum found

Dry Run

Let's trace through Example 1: nums = [-2,1,-3,4,-1,2,1,-5,4]

Kadane's Algorithm:

Solution

⚠️ Disclaimer: Don't jump directly to the solution, try it out yourself first. Only look at the solution after you've given it a good attempt.

Solution 1: Kadane's Algorithm (Optimal)

Time Complexity: O(n) - We traverse the array once

Space Complexity: O(1) - Only need a few variables

Solution 2: Dynamic Programming

Time Complexity: O(n) - We traverse the array once

Space Complexity: O(n) - Need DP array

Solution 3: Brute Force

Time Complexity: O(n²) - We check all subarrays

Space Complexity: O(1) - Only need a few variables

More Capgemini coding questions