Kadane's Algorithm

Arrays FAQs(Medium) Medium

Given an integer array nums, find the subarray with the largest sum and return the sum of the elements present in that subarray.


A subarray is a contiguous non-empty sequence of elements within an array.

Examples:

Input: nums = [2, 3, 5, -2, 7, -4]

Output: 15

Explanation: The subarray from index 0 to index 4 has the largest sum = 15

Input: nums = [-2, -3, -7, -2, -10, -4]

Output: -2

Explanation: The element on index 0 or index 3 make up the largest sum when taken as a subarray

Input: nums = [-1, 2, 3, -1, 2, -6, 5]

Constraints

  • 1 <= nums.length <= 105
  • -104 <= nums[i] <= 104

Hints

  • "Maintain two variables: currentMax: Tracks the maximum sum ending at the current index. globalMax: Stores the maximum sum seen so far."
  • If adding the current element decreases the sum, start a new subarray from the current element. This happens when the previous sum becomes negative.

Company Tags

Activision Blizzard Broadcom Teladoc Health Roche Zomato Pinterest Optum Epic Systems Twilio Rockstar Games Siemens Healthineers Red Hat McKinsey & Company Oracle Cloudflare Mastercard Salesforce Seagate Technology Qualcomm Flipkart Bain & Company PwC Electronic Arts Swiggy Philips Healthcare Google Microsoft Amazon Meta Apple Netflix Adobe