1.题目描述
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.
2.解法分析
略加思索,这个题目就有了一个递归的解法,但递归的解法在写的过程中自己就有了疑问,那就是是否会TLE,结果大数据集果然TLE了,
return max(max(__maxArea(height,begin+1,end),__maxArea(height,begin,end-1)),min(height[begin],height[end])*(end-begin));
}
};
然后就考虑是不是有地方被重复计算了,一看果不其然,那么就用动态规划改写吧。
return dp[0];
}
};
结果时间是缩短了,但是还是在大数据集上TLE了,这说明我最初的算法可能有问题。最终看discuss里面的算法,豁然开朗,自己最初的想法差点到了这个点,却一闪而过,看来算法功底还有待加强。算法代码如下:
return globalMax;
}
};
总结:递归太自然,让人太舒服,但是不一定是最好的解法。