Kadane's Algorithm

Arrays FAQs(Medium) Medium
  • This problem, often referred to as the Maximum Subarray Problem, forms the basis for many real-world applications in the field of Financial Technology
  • One key application is in the analysis of stock prices
  • Given the changes in a stock's price over a sequence of time (which can be positive or negative), the maximum subarray problem can be used to determine the most profitable time to buy and sell for maximum profit
  • The subarray with the largest sum essentially represents the period with the most significant growth
  • The Kadane's algorithm, often used to solve this problem, is widely used in such financial analysis systems, reinforcing how theoretical computer science problems have direct, practical implications

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