LeetCode 算法学习(6)

题目描述

Container With Most Water
Given n non-negative integers a1, a2, …, an , where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water.
Note: You may not slant the container and n is at least 2.
avatar

Example
Input: [1,8,6,2,5,4,8,3,7]
Output: 49

题目大意

在给出的一串数列中,寻找出两个数,它们所构成的“容器”的容量(最小高度*间距)最大。

思路分析

经典的动态规划,设置两个指针,一个从头开始遍历,一个从尾部开始遍历,直到两者相遇;要找到“容量”最大,由短板效应想到,就是要淘汰掉“短板”,就是说比较小的那一端向后(前)遍历;这样就保证了“短板”被淘汰。时间复杂度为O(n),空间复杂度为O(1)。

关键代码

    int maxArea(vector<int>& height) {
        int result = 0;
        int n = height.size();
        int p = 0, q = n-1;
        while (p < q) {
            int minpq = (height[p] < height[q]) ? height[p] : height[q];
            int tempArea = minpq*(q-p);
            if (height[q] > height[p]) { // 淘汰短板
                p++;
            } else {
                q--;
            }
            result = (tempArea > result) ? tempArea : result;
        }
        return result;
    }

总结

这是一道经典的动态规划题,这里动态规划的子问题显然是“向前还是向后遍历可以使得容量更大”,也就是说该淘汰哪一块板;再从这些子问题中找出最优解。
而根据题目所描述的,可以想到选择这两块板的初始位置,从而解决该问题。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值