Leetcode Dynamic planning trapping Rain water

Source: Internet
Author: User

This article is Senlie original, reprint please retain this address:Http://blog.csdn.net/zhengsenlie


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

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

For example,
Given [0,1,0,2,1,0,1,3,2,1,2,1] , return 6 .


The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of the Rain Water (blue section) is being trapped. Thanks Marcos for contributing this image!




Test instructions: There is an array representing the height of n pillars a[i], calculating the maximum amount of water that can be saved by the slots between these columns
Idea: Left and right DP
Use an array of left[i] to indicate the height of the highest pillar on the left of the pillar I
Use an array of right[i] to indicate the height of the highest pillar to the right of the pillar I
1. Scan from left to right, left[i] = max (left[i-1], a[i-1])
2. Right-to-left scan, right[i] = max (right[i + 1], A[i + 1])
3. The water on the pillar I can save is min (Left[i], right[i])-a[i], because at this time left[i] is useless, it can be used to store this value.
Complexity: Time O (n), space O (n)

Related Topics:

Candy

Longest palindromic Substring

int trap (int a[], int n) {if (n = = 3) return 0;vector<int> Left (n, 0), right (n, 0), and 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] = m In (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;}


Leetcode Dynamic planning trapping Rain water

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.