Leetcode-Solutions

My Leetcode Solutions.

View on GitHub

209. Minimum Size Subarray Sum

Topics: Array Binary Search Sliding Window Prefix Sum

Solution

Implementation

class Solution {
    fun minSubArrayLen(target: Int, nums: IntArray): Int {
        var result: Int? = null
        var currentSum = nums[0]
        var l = 0
        var r = 0

        while (l < nums.size || r < nums.size) {
            if (currentSum >= target) {
                val p = r - l + 1
                if (result == null || result > p) result = p
                currentSum -= nums[l++]
            } else {
                if (r == nums.lastIndex) break
                currentSum += nums[++r]
            }
        }

        return result ?: 0
    }
}