LeetCode – 1827. Minimum Operations to Make the Array Increasing

題目連結:

https://leetcode.com/problems/minimum-operations-to-make-the-array-increasing/

參考解法:

https://leetcode.com/problems/minimum-operations-to-make-the-array-increasing/discuss/1502527/Swift-Simple-solution

法ㄧ(Time complexity: O(n) 、Space complexity: O(n) )

    func minOperations(_ nums: [Int]) -> Int {
        var i = 0
        var result = 0
        var arr = nums
        while i < nums.count - 1 {
            if arr[i+1] <= arr[i] {
                result += arr[i] - arr[i+1] + 1
                arr[i+1] = arr[i] + 1
            }
            i += 1
        }
        return result
    }

法二(Time complexity: O(n) 、Space complexity: O(1) )

    func minOperations(_ nums: [Int]) -> Int {
        var result = 0
        var lastNum = 0
        for i in 0 ..< nums.count {
            if i != 0 && nums[i] <= lastNum {
                result += (lastNum - nums[i] + 1)
                lastNum = lastNum + 1
            } else {
                lastNum = nums[i]
            }
        }
        return result
    }