அல்கோரிதம்dp speedup

DP-ஐ வேகப்படுத்த Binary Search

TT
Testlaa Team
May 14, 20261 min read

DP monotone f(k)k binary search; அல்லது convex cost transitions.

Try this in Python

def min_groups_linear_time_threshold(nums: list[int], limit: int) -> int:
    """Greedy groups with sum <= limit (not always optimal globally; pedagogy)."""
    g, s = 1, 0
    for x in nums:
        if s + x <= limit:
            s += x
        else:
            g += 1
            s = x
    return g


def bs_min_limit(nums: list[int], max_groups: int) -> int:
    lo, hi = max(nums), sum(nums)
    while lo < hi:
        mid = (lo + hi) // 2
        if min_groups_linear_time_threshold(nums, mid) <= max_groups:
            hi = mid
        else:
            lo = mid + 1
    return lo


print(bs_min_limit([10, 2, 20, 5], 2))

Key takeaways

  • இது கல்வி உதாரணம்; எல்லா DP-க்கும் பொருந்தாது.
  • சரியான check model தேவை.
  • partition lesson உடன் இணைத்துப் படி.

Tags:

Binary searchPythonமாணவர்கள்