Maximum Subarray Sum
Updated
Problem statement
Given an integer array nums, return the largest sum of any nonempty contiguous subarray.
A subarray uses consecutive positions and must contain at least one element. You cannot skip elements inside it or choose an empty array. For example, when all entries are negative, return the greatest single entry. For this exercise, return the sum rather than indices or values and leave nums unchanged.
Function
maxSubarraySum(nums: int[]) → intExamples
Example 1
nums = [3,-4,5,-1,2,-6]return = 6The contiguous subarray [5,-1,2] at indices 2 through 4 has sum 6. No nonempty interval has a larger sum. Selecting 3 as well would require including -4 and would give only 5.
Example 2
nums = [-7,-2,-5]return = -2Every nonempty interval is negative. The singleton [-2] has the greatest sum, -2; choosing an empty subarray with sum 0 is forbidden.
Constraints
- For this exercise, assume 1 <= nums.length <= 2000.
- For this exercise, assume -1000000 <= nums[i] <= 1000000.
More Morgan Stanley Online Assessment questions
- Three-Resource 0/1 KnapsackOA · Seen Sep 2026
- Maximum Concurrent ProcessesOA · ONSITE INTERVIEW · Seen Sep 2026
- Maximum Total of Nonadjacent RatingsOA · Seen Jul 2026
- Count Shipment SchedulesOA · Seen Apr 2026
- Delete and EarnOA · Seen Apr 2026
- Interleave Array HalvesOA · Seen Apr 2026
- Get Patch SequenceOA · Seen Feb 2025
- String Subsequences 🐳OA · Seen Mar 2024
- Binary Tree Level OrderOA · Seen Feb 2024
- Merge IntervalsOA · Seen Feb 2024
Similar questions at other companies
- 0/1 KnapsackConfluent · OAConfluent interview questions
- Minimum Cost to Tile a Strip with Widths 1, 2, and 3Infosys · OAInfosys interview questions
- Maximum Escape Game ScoreMicrosoft · OAMicrosoft interview questions
- Maximum Subarray SumStraive · OA
- Longest Increasing Price SubsequenceOpenAI · OAOpenAI interview questions
- Lowest-Cost Shirt Color ScheduleElevenLabs · OAElevenLabs interview questions
- Maximum Game Board ScoreJP Morgan Chase · OAJP Morgan Chase interview questions
- API Bandwidth AllocationArista Networks · OAArista Networks interview questions
- Maximum Points by Deleting ElementsIBM · OAIBM interview questions
- House RobberWalmart · OAWalmart interview questions
Interview reports that mention this question
Morgan Stanley interview experiences
- Morgan Stanley Apprenticeship and Tech Interviews: 6 Experiences
- Morgan Stanley Intern Oldest Loops: 5 Experiences (Part 5 of 5)
- Morgan Stanley Intern OOP Loops: 5 Experiences (Part 4 of 5)
- Morgan Stanley Intern Earlier Loops: 5 Experiences (Part 3 of 5)
- Morgan Stanley Intern Tech Rounds: 5 Experiences (Part 2 of 5)