Algorithm: Max Counters

后端 未结 22 1670
孤城傲影
孤城傲影 2021-02-04 07:40

I have the following problem:

You are given N counters, initially set to 0, and you have two possible operations on them:

  • increase(X) − counter X is increa
22条回答
  •  你的背包
    2021-02-04 08:27

    Swift solution 100%

    public func solution(_ N : Int, _ A : inout [Int]) -> [Int] {
        // write your code in Swift 4.2.1 (Linux)
    
        var solution = Array.init(repeating: 0, count: N)
    
            var max = 0
            var actualMaxValue = 0
    
            for obj in A {
    
                if (obj <= N && obj >= 1 ) {
    
                    if solution[obj-1] < actualMaxValue {
    
                        solution [obj-1] = actualMaxValue + 1
                    } else {
    
                        solution[obj-1] += 1
                    }
    
                    if (solution[obj-1] > max) {
    
                        max = solution[obj-1]
                    }
                }
                else if obj == N+1 {
    
                  actualMaxValue = max
                }
            }
    
        for (index, value) in solution.enumerated() {
    
    
            if value < actualMaxValue {
    
                solution[index] = actualMaxValue
            }
        }
    
    
        return solution
    }
    

提交回复
热议问题