Container With Most Water

Sett·2021년 8월 16일
0

문제

https://leetcode.com/problems/container-with-most-water/

문제 접근

  1. 물을 많이 채우라고 하시네요.
  2. 가장 큰 수를 찾아서 그걸 기준으로 해볼까..? 하다가 작아도 가로가 길면? 이라는 예외가 생각나서 패스
  3. 그럼 그냥 하나하나 다 따져봐야겠네..?
  4. 이중 포문으로 해볼까..?? 시간초과남 ㅋ
func maxArea(_ height: [Int]) -> Int {
    var result = 0
    for i in 0..<height.count {
        for j in (i+1)..<height.count {
            let subject = min(height[i], height[j])
            let tempResult = subject * abs(i-j)
            if result < tempResult {
                result = tempResult
            }
        }
    }
    return result
}
  1. 같은 방법인데 2중 포문만 날려서 해보기로 함. (index 때문에 2중 포문 썼는 데 index 외부에서 주고 while문으로 처리하기)

  2. 근데 어차피 같은 방법인데 아래 같이 쓰다가 막힘.

var result = 0
        var index1 = 0
        let index2 = height.count - 1
        while index1 < index2 {
            let subject = min(height[index1], height[index2])
            let width = abs(index1 - index2)
            let water = subject * width
            result = max(result, water)
            index1 += 1
        }
        return result
  1. 다른 사람 거 참고 했는데 아래와 같이 조건을 넣어줌
if height[index1] < height[index2] {
    index1 += 1
}
else {
    index2 -= 1
}
  1. 최대한 큰 숫자 끼리만 해보려고 이러한 식을 넣은게 아닐까 추측해 봄
    정확히는 모르겠네..요..?

소스 코드

        var result = 0
        var index1 = 0
        var index2 = height.count - 1
        while index1 < index2 {
            let subject = min(height[index1], height[index2])
            let width = abs(index1 - index2)
            let water = subject * width
            result = max(result, water)
            if height[index1] < height[index2] {
                index1 += 1
            }
            else {
                index2 -= 1
            }
        }
        return result
profile
안녕하세요

0개의 댓글

관련 채용 정보