Skip to main content

Sliding Window: Dynamic

dynamic_sliding_window.gif

def dynamic_sliding_window(find_all_subarrays(nums, target):
    """
    Prints the steps of a dynamic sliding window algorithm.
    Given an array of positive integersFinds and aprints target sum, the algorithm finds
    aall contiguous subarray (window)subarrays whose sum is as close as possible to, but does not exceed,equals the target.
    Assumes that all numbers in 'nums' are positive.
    """
    print("Problem: Given an array of positive integers and a target sum,")
    print("find aall contiguous subarraysubarrays whose sum is as close as possible to, but does not exceed,equals the target."\n")
    print(f"Example: nums = {nums}, target = {target}"\n")
    print("-" * 70)
    
    left = 0
    current_sum = 0
    n = len(nums)
    
    # StartIterate processingwith 'right' pointer to expand the array with a sliding windowwindow.
    for right in range(len(nums))n):
        current_sum += nums[right]
        print(f"\nExpandingExpanding window: added nums[{right}] = {nums[right]}")
        print(f"Current window (indices [{left} to {right}]): {nums[left:right+1]}")
        print(f"Current sum: {current_sum}"\n")
        
        # ContractIf the sum exceeds the target, contract the window from the left if the current sum exceeds the target.left.
        while current_sum > target and left <= right:
            print(f"  Sum {current_sum} exceeds target {target}.")
            print(f"  Removing nums[{left}] = {nums[left]} from window.")
            current_sum -= nums[left]
            left += 1
            print(f"  After contraction, new window (indices [{left} to {right}]): {nums[left:right+1]}")
            print(f"  Current sum: {current_sum}"\n")
        
        # If the current sum equals the target, print the subarray.
        if current_sum == target:
            print(f"Found subarray with sum {target}: indices [{left}, {right}] -> {nums[left:right+1]}\n")
    
    print("-" * 70)
    print(f"Final"Done windowsearching (fromfor index {left} to end): {nums[left:]}")
    print(f"Final sum: {current_sum}subarrays.")

# Example usage:
nums = [1, 3, 2, 5, 1, 1, 2, 1, 4]
target = 8
dynamic_sliding_window(find_all_subarrays(nums, target)