Algorithm ๐Ÿง‘๐Ÿป‍๐Ÿ’ป/Leetcode

[Leetcode,c++] Container With Most Water

dkswnkk 2021. 11. 14. 18:08

๋ฌธ์ œ

 

Container With Most Water - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

์ฝ”๋“œ

class Solution {
public:
    int maxArea(vector<int>& height) {
        int start = 0;
        int end = height.size()-1;

        int ans = -1;
        while(start<=end){
            int x = end-start;
            int y = min(height[start],height[end]);
            ans = max(ans,x*y);

            if(height[start]<height[end]) start++;
            else end--;
        }
        return ans;
    }
};

ํ’€์ด

ํˆฌ ํฌ์ธํ„ฐ๋ฅผ ํ™œ์šฉํ•˜์—ฌ ์‹œ๊ฐ„ ๋ณต์žก๋„ O(N)๋กœ ํ•ด๊ฒฐํ•œ ํ’€์ด์ž…๋‹ˆ๋‹ค.

๋ฐฐ์—ด์˜ ์ฒ˜์Œ๊ณผ ๋์„ ๋น„๊ตํ•˜๋Š”๋ฐ ๋‘˜์ค‘ ์ž‘์€ ์ชฝ์„ ๋‹ค์Œ ์ธ๋ฑ์Šค๋กœ ๋„˜๊ธฐ๋Š” ๋ฐฉ์‹์œผ๋กœ ๊ตฌํ˜„ํ–ˆ์Šต๋‹ˆ๋‹ค.