{ "cells": [ { "cell_type": "markdown", "source": [ "Given an array of **n** positive integers and a positive integer **s** , find\n", "the minimal length of a **contiguous** subarray of which the sum ≥ **s**. If\n", "there isn't one, return 0 instead.\n", "\n", "**Example: **\n", "\n", "\n", "\n", " Input: s = 7, nums = [2,3,1,2,4,3]\n", " Output: 2\n", " Explanation: the subarray [4,3] has the minimal length under the problem constraint.\n", "\n", "**Follow up:**\n", "\n", "If you have figured out the _O_ ( _n_ ) solution, try coding another solution\n", "of which the time complexity is _O_ ( _n_ log _n_ )." ], "metadata": {} }, { "outputs": [ { "output_type": "execute_result", "data": { "text/plain": "min_subarray_len (generic function with 1 method)" }, "metadata": {}, "execution_count": 1 } ], "cell_type": "code", "source": [ "# @lc code=start\n", "using LeetCode\n", "\n", "function min_subarray_len(s::Int, nums::Vector{Int})\n", " left = right = 1\n", " res = typemax(Int)\n", " len = length(nums)\n", " Σ = nums[1]\n", " while right <= len\n", " if Σ == s\n", " res = min(res, right - left + 1)\n", " Σ -= nums[left]\n", " left += 1\n", " right += 1\n", " (right <= len) && (Σ += nums[right])\n", " elseif Σ < s\n", " right += 1\n", " (right <= len) && (Σ += nums[right])\n", " else\n", " Σ -= nums[left]\n", " left += 1\n", " end\n", " end\n", " res\n", "end\n", "# @lc code=end" ], "metadata": {}, "execution_count": 1 }, { "cell_type": "markdown", "source": [ "---\n", "\n", "*This notebook was generated using [Literate.jl](https://github.com/fredrikekre/Literate.jl).*" ], "metadata": {} } ], "nbformat_minor": 3, "metadata": { "language_info": { "file_extension": ".jl", "mimetype": "application/julia", "name": "julia", "version": "1.10.1" }, "kernelspec": { "name": "julia-1.10", "display_name": "Julia 1.10.1", "language": "julia" } }, "nbformat": 4 }