Skip to content

Latest commit

 

History

History
77 lines (58 loc) · 1.8 KB

LC325.md

File metadata and controls

77 lines (58 loc) · 1.8 KB

Problem: Maximum Size Subarray Sum Equals K

Difficulty: Medium

Description:

Given an array nums and a target value k, find the maximum length of a subarray that sums to k. If there isn’t one, return 0 instead.

Examples:

Input: nums = [1, -1, 5, -2, 3], k = 3
Output: 4
Explanation: The subarray [1, -1, 5, -2] sums to 3 and is the longest.
Input: nums = [-2, -1, 2, 1], k = 1
Output: 2
Explanation: The subarray [-1, 2] sums to 1 and is the longest.

Constraints:

The length of the given binary array will not exceed 50,000.

Solutions:

The naive appraoch is always to produce all of the subarrays and find the one that meets the objective. This approach has a time complexity of O(N^3) and space complexity of O(N) where N is the size of array.

def maxSubArrayLen(nums, k):
    """
    :type nums: List[int]
    :rtype: int
    :Time Complexity: O(N^3)
    :Space Complexity: O(N)
    """
    maxLen = 0

    for i in range(len(nums)):
        for j in range(i, len(nums)):
            sub = nums[i : j + 1]
            if sum(sub) == k:
                maxLen = max(maxLen, len(sub))

    return maxLen

For the optimal solution, we can use the Prefix-Sum algorithm. This approach has a time complexity of O(N) and space complexity of O(N) where N is the size of array.

def maxSubArrayLen(nums, k):
    """
    :type nums: List[int]
    :rtype: int
    :Time Complexity: O(N)
    :Space Complexity: O(N)
    """
    maxLen = 0
    current_sum = 0
    seen = {0: -1}

    for i in range(len(nums)):
        current_sum += nums[i]

        if current_sum not in seen:
            seen[current_sum] = i

        remainder = current_sum - k

        if remainder in seen:
            maxLen = max(maxLen, i - seen[remainder])

    return maxLen