Maximum Subarray
Maximum Subarray is a Medium Data Structures and Algorithms interview problem you can solve, run and submit on Thita.ai. It belongs to the Dynamic Programming (DP) Patterns pattern, in the 1D Array (Kadane's Algorithm for Max/Min Subarray) subpattern.
Problem statement
Given an integer array nums, find the subarray with the largest sum, and return its sum.
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.
Constraints:
- 1 <= nums.length <= 105
- -104 <= nums[i] <= 104
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.
Topics and companies
Topics: Array, Divide and Conquer, Dynamic Programming.
Reported in interviews at Adobe, Amazon, Apple, Bloomberg, ByteDance, Cisco, Facebook, Google, JPMorgan, LinkedIn, Microsoft, Oracle and others.
How to practise Maximum Subarray on Thita.ai
Starter code is provided in C, C#, C++, Go, Java, JavaScript and Python. Your solution runs against 5 test cases for this problem, with the AI coach available for a hint when you are stuck rather than a finished answer. The reference solution runs in O(n) time and O(1) space.
Open Maximum Subarray in the code editor, or read the Maximum Subarray editorial for a worked solution with its approach and complexity analysis.
Where Maximum Subarray sits in the DSA pattern sheet
- Dynamic Programming (DP) Patterns pattern guide
- 1D Array (Kadane's Algorithm for Max/Min Subarray) subpattern
- The full DSA patterns sheet
- All coding practice problems
Problems related to Maximum Subarray
Other problems that use the same 1D Array (Kadane's Algorithm for Max/Min Subarray) and Dynamic Programming (DP) Patterns techniques:
- Maximum Absolute Sum of Any Subarray — Medium, same subpattern
- Maximum Product Subarray — Medium, same subpattern
- Maximum Sum Circular Subarray — Medium, same subpattern
- Best Time to Buy and Sell Stock — Easy, same pattern
- Best Time to Buy and Sell Stock II — Medium, same pattern
- Best Time to Buy and Sell Stock III — Hard, same pattern
Opening the problem
Progress is saved as you study.