Elegant swift solution


  • 0
    K
    class Solution {
          func canCompleteCircuit(_ gas: [Int], _ cost: [Int]) -> Int {
    
    
            for startIndex in 0 ..< gas.count {
                let endIndex = ((startIndex - 1) >= 0 ? startIndex - 1 : gas.count - 1)
    
                var leftGas: Int = 0
                for index in startIndex ..< gas.count + startIndex {
                    let index = index % gas.count
    
                    leftGas += gas[index] - cost[index]
                    if leftGas < 0 {
                        break
                    }
                    if index == endIndex {
                        return startIndex
                    }
                }
            }
    
            return -1
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.