মূল কনটেন্টে যান
🛰️
রিমোট DSA
প্যাটার্নটপিক 1 · Arrays & Strings

1.6 Kadane's Algorithm

চিনবেন কীভাবে
"maximum/minimum subarray sum", contiguous, a running best in one pass — really a one-variable DP: "extend the previous run, or start fresh?"
Demo · approach · কোড — আগে নিজে চেষ্টা, আটকালে খুলুন

Demo: Maximum SubarrayLC 53 (Medium)

Statement (Demo): Given an integer array nums, find the contiguous subarray with the largest sum and return that sum. Example: [-2,1,-3,4,-1,2,1,-5,4]6 | ⚡ n ≤ 10⁵, -10⁴ ≤ nums[i] ≤ 10⁴

Approach: At each index decide: if the running sum still helps, extend it; otherwise start a new subarray here. Keep the global best separately.

function maxSubArray(nums) {
  let cur = nums[0],
    best = nums[0];
  for (let i = 1; i < nums.length; i++) {
    cur = Math.max(nums[i], cur + nums[i]); // start fresh vs extend
    best = Math.max(best, cur);
  }
  return best;
}

Complexity: Time O(n), Space O(1)

Demo · Maximum Subarrayplan · দিন ০২৩LC 53
নোট · ফাঁকা

প্রবলেম

  • Maximum Product SubarrayLC 152
    (negative × negative = positive → track the min too)

    Statement: Given an integer array nums, find the contiguous subarray with the largest product and return that product.
    Example: [2,3,-2,4]6 ([2,3]) | ⚡ n ≤ 2×10⁴, -10 ≤ nums[i] ≤ 10

    নোট · ফাঁকা