Tensorum
YouTubeಕಲಿಯಲು ಪ್ರಾರಂಭಿಸಿ
LeetCode 134 · Jump / Reachability

Gas Station

LeetCode 134 · ಮಧ್ಯಮ · ಪರಿಹಾರ, intuition ಮತ್ತು ಹಂತ ಹಂತದ ವಾಕ್‌ಥ್ರೂ

Reset the start after any negative running tank.

ಮಧ್ಯಮArrayGreedy
LeetCode ನಲ್ಲಿ ತೆರೆಯಿರಿ ↗

ನಾನು Gas Station (LeetCode 134) ಅನ್ನು ಹೀಗೆ ಪರಿಹರಿಸಿದೆ — Jump / Reachability ಪ್ಯಾಟರ್ನ್‌ನ ಒಂದು ಮಧ್ಯಮ ಪ್ರಾಬ್ಲಮ್. ಕೆಳಗೆ: intuition, ಹಂತ ಹಂತದ approach, ನನ್ನ accepted Python ಕೋಡ್, animated test cases ಮತ್ತು line-by-line debugger.

ಕೆಳಗಿನ ವಿವರಣೆ ಇಂಗ್ಲಿಷ್‌ನಲ್ಲಿದೆ.

Intuition

If total gas is less than total cost, no start works. Otherwise drive from a candidate start keeping a running tank; if the tank goes negative at i, no station between the start and i can work either, so restart from i + 1.

Approach

  1. 1

    Total check → −1 if impossible.

  2. 2

    Accumulate gas[i] − cost[i].

  3. 3

    Negative → start = i + 1, tank = 0.

  4. 4

    Return start.

ನಾನು ಹೇಗೆ ಪರಿಹರಿಸಿದೆ

Greedy single passPythonO(n) time · O(1) space
class Solution:
    def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:
        if sum(cost)>sum(gas):
            return -1
        i=0
        start=0
        effort = 0
        while i<len(gas):
            effort += gas[i]-cost[i]
            if effort<0:
                effort=0
                start=i+1
            i+=1
        return start
ಸ್ಟೆಪ್-ಥ್ರೂ ಲೋಡ್ ಆಗುತ್ತಿದೆ…

Gas Station — ಪದೇ ಪದೇ ಕೇಳುವ ಪ್ರಶ್ನೆಗಳು

Gas Station ಹಿಂದಿನ intuition ಏನು?

If total gas is less than total cost, no start works. Otherwise drive from a candidate start keeping a running tank; if the tank goes negative at i, no station between the start and i can work either, so restart from i + 1.

Gas Station (LeetCode 134) ಅನ್ನು ಹೇಗೆ ಪರಿಹರಿಸುವುದು?

1. Total check → −1 if impossible. 2. Accumulate gas[i] − cost[i]. 3. Negative → start = i + 1, tank = 0. 4. Return start.

Gas Station ನ time ಮತ್ತು space complexity ಎಷ್ಟು?

Time: O(n). Space: O(1). (Accepted approach: Greedy single pass.)

Gas Station ನಲ್ಲಿ ಸಾಮಾನ್ಯ ತಪ್ಪುಗಳು ಯಾವುವು?

The total check is what guarantees the found start completes the loop.