00:00

Problem Statement

Input/Output Examples

Visual Explanation

current = max(value, current + value) drops any prefix whose sum has become negative, because such a prefix can only make later sums smaller.

Approaches

Both approaches are linear. Kadane's algorithm tracks the best sum ending at each position; the prefix-sum version subtracts the smallest earlier prefix.

Java Solutions

Each tab is a complete program that runs on Java 17 or later. Both programs print the same output for the same inputs.

Complexity Analysis

Here n is the number of elements. Both approaches read each value once with a few variables; checking every subarray would take O(n²).

Interview Tips and Recommended Approach

  • Handle all-negative input. Initialising best to 0 returns a wrong answer for [-3, -1, -2].
  • Track the indexes if asked. Record the start whenever a fresh subarray begins.
  • Know the circular variant. It combines Kadane's maximum with the total minus the minimum subarray.
  • Explain why it is dynamic programming. Each current value depends only on the previous one.

Recommended Approach: Kadane's Algorithm

Why: it is the classic linear-time solution, uses two variables and handles every input, including all-negative arrays.