Leetcode dynamic planning Trapping Rain Water, leetcodetrapping

Source: Internet
Author: User

Leetcode dynamic planning Trapping Rain Water, leetcodetrapping

This article is senlie original, reproduced Please retain this address: http://blog.csdn.net/zhengsenlie


Trapping Rain Water Total Accepted: 14568 Total Submissions: 50810My Submissions

Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.

For example,
Given[0,1,0,2,1,0,1,3,2,1,2,1], Return6.


The above elevation map is represented by array [,]. in this case, 6 units of rain water (blue section) are being trapped. thanks Marcos for contributing this image!




There is an array A [I] that represents the height of n columns. Calculate the maximum amount of water saved between these columns.
Idea: Left and Right dp
Use an array left [I] to indicate the height of the highest column on the left of the column I
Use an array right [I] to indicate the height of the highest column on the right of the column I
1. left-to-right scan, left [I] = max (left [I-1], A [I-1])
2. right [I] = max (right [I + 1], A [I + 1])
3. the water saved on column I is min (left [I], right [I])-A [I], because left [I] is useless, you can use it to store this value.
Complexity: time O (n), Space O (n)

Related questions:

Candy



int trap(int A[], int n){if (n == 3) return 0;vector<int> left(n, 0), right(n, 0);for(int i = 1; i < n - 1; ++i) left[i] = max(left[i - 1], A[i - 1]);for(int i = n - 2; i > 0; --i) {right[i] = max(right[i + 1], A[i + 1]);left[i] = min(left[i], right[i]) - A[i];}int sum = 0;for_each(left.begin() + 1, left.end() - 1, [&sum](int c){if(c > 0) sum += c;});return sum ;}





Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.