Skip to content

Conversation

@docto-rin
Copy link
Owner

- うーん、いきなりsliding windowでやったから再検討が必要。
- まず原点回帰して、最もナイーブには全探索で、O(n^2)となる。
- しかし、内側のループは無駄が多そう。
- 前からの累積和は単調増加するので、二分探索(lower bound)で初めて和がtarget以上になる点がわかる。
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

半分に割って分割統治することを繰り返すという方法があります。中央をまたぐ場合とまたがない場合に分類します。

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ありがとうございます。

書いてみました。

class Solution:
    def minSubArrayLen(self, target: int, nums: list[int]) -> int:
        if target <= 0:
            raise ValueError(f"target '{target}' must be positive")
        if not nums:
            return 0
        
        INF = len(nums) + 1

        def calc_min_length(left, right):
            if left == right:
                if nums[left] >= target:
                    return 1
                return INF

            mid = (left + right) // 2
            left_min_length = calc_min_length(left, mid)
            right_min_length = calc_min_length(mid + 1, right)
            min_length = min(left_min_length, right_min_length)
            
            i = mid
            j = mid + 1
            total = 0
            # invariant: total = sum(nums[i:j])
            while i >= left:
                total += nums[i]
                while total < target and j <= right:
                    total += nums[j]
                    j += 1
                if total >= target:
                    min_length = min(min_length, j - i)
                i -= 1
            
            return min_length
        
        min_length = calc_min_length(0, len(nums) - 1)
        if min_length == INF:
            return 0
        return min_length

for left in range(len(nums)):
right = bisect.bisect_left(prefix_sum, target + prefix_sum[left])
if right == len(prefix_sum):
continue

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

break でいいでしょうか?

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ありがとうございます。

breakでいいですね。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants