leetcode 11. Container With Most Water

旧城等待, 2022-07-26 08:41 237阅读 0赞

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.

  1. class Solution {
  2. public:
  3. int maxArea(vector<int>& height) {
  4. int heightSize = height.size();
  5. if (height.empty())
  6. return 0;
  7. if (heightSize < 2)
  8. return 0;
  9. int index=0;
  10. for (int i = 0; i < height.size(); i++)
  11. if (height[i]>height[index])
  12. index= i;
  13. if (height[index] == 0)
  14. return 0;
  15. int max = 0;
  16. vector<int>starter(heightSize);
  17. if (index < height.size() / 2)
  18. {
  19. int nxt = 0; int i = 0;
  20. bool f = false;
  21. while (!f&&i < heightSize - 1)
  22. {
  23. if (height[i] == 0)
  24. i++;
  25. else
  26. {
  27. f = true;
  28. i = nxt;
  29. nxt = heightSize;
  30. if (starter[i] == 0)
  31. {
  32. for (int j = i + 1; j < heightSize; j++)
  33. {
  34. if (height[j] <= height[i])
  35. starter[j] = 1;
  36. else
  37. {
  38. if (f)
  39. {
  40. nxt = j;
  41. f = false;
  42. }
  43. }
  44. int h = height[i] < height[j] ? height[i] : height[j];
  45. if (h*(j - i)>max)
  46. max = h*(j - i);
  47. }
  48. }
  49. }
  50. }
  51. }
  52. else
  53. {
  54. int nxt = heightSize - 1; int i = heightSize - 1;
  55. bool f = false;
  56. while (!f&&i >= 1)
  57. {
  58. if (height[i] == 0)
  59. i--;
  60. else
  61. {
  62. f = true;
  63. i = nxt;
  64. nxt = 0;
  65. if (starter[i] == 0 && height[i] > 0)
  66. {
  67. for (int j = i - 1; j >= 0; j--)
  68. {
  69. if (height[j] <= height[i])
  70. starter[j] = 1;
  71. else
  72. {
  73. if (f)
  74. {
  75. nxt = j;
  76. f = false;
  77. }
  78. }
  79. int h = height[i] < height[j] ? height[i] : height[j];
  80. if (h*(i - j)>max)
  81. max = h*(i - j);
  82. }
  83. }
  84. }
  85. }
  86. }
  87. return max;
  88. }
  89. };

accept

发表评论

表情:
评论列表 (有 0 条评论,237人围观)

还没有评论,来说两句吧...

相关阅读