Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improvements for Trapping Rain water Problem. #245

Open
iHackSubhodip opened this issue May 16, 2019 · 0 comments
Open

Improvements for Trapping Rain water Problem. #245

iHackSubhodip opened this issue May 16, 2019 · 0 comments

Comments

@iHackSubhodip
Copy link
Contributor

iHackSubhodip commented May 16, 2019

Here I just tried to improve the space complexity.

your Solution ->

https://github.com/soapyigu/LeetCode-Swift/blob/master/Math/TrappingRainWater.swift

Mine with -> O(n) TC and O(1) SC

`
class Solution {
func trap(_ height: [Int]) -> Int {
var waterContainerResult = 0
var left = 0, right = height.count - 1, leftMax = 0, rightMax = 0

    while left < right{
        if height[left] < height[right]{
            if height[left] >= leftMax{
                leftMax = height[left]
            }else{
                waterContainerResult = waterContainerResult + leftMax - height[left]
            }
            left += 1
        }else{
            if height[right] >= rightMax{
                rightMax = height[right]
            }else{
                waterContainerResult = waterContainerResult + rightMax - height[right]
            }
            right -= 1
        }
    }

    return waterContainerResult
}

}
`

Runtime: 28 ms, faster than 93.62% of Swift online submissions for Trapping Rain Water.
Memory Usage: 20.9 MB, less than 5.01% of Swift online submissions for Trapping Rain Water.

If it looks fine, I will raise a PR for this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant