[Leetcode]42 trapping Rain water

Source: Internet
Author: User

https://oj.leetcode.com/problems/trapping-rain-water/

Http://fisherlei.blogspot.com/2013/01/leetcode-trapping-rain-water.html


Public class solution {    public int trap (Int[] A)  {                      //  for a coordinate   has         // - leftmax  It left highest         // - rightmax  it right up          // - val  it itself highly         //   then its volume is  max ( min (Leftmax, rightmax)  - val, 0 )                  //  traverse from left to right   create   leftmax[]        //  similar   right-to-left traversal   Create  rightmax[]         //  finally traverse through   calculate volume   sum          // o (n)                 // Input  validations.        if  (a == null | |  a.length == 0)             return  0;   // Invalid input.                 int len = A.length;                 // Build leftmax[]         int[] leftmax = new int[len];         int seenleftmax = 0;        for   (int i = 0 ; i < len ; i ++)          {            leftmax[i] = seenleftmax;             if  (A[i] > seenleftmax)                  seenleftmax =  A[i];        }                 // Build rightmax[]         int[] rightmax = new int[len];         int seenrightmax = 0;        for  (int i  = len - 1 ; i >= 0 ; i --)          {            rightmax[i]  = seenrightmax;            if  (A[i] >  Seenrightmax)                  seenrightmax = a[i];        }                 // Calculate result         int result = 0;         for  (int i = 0 ; i < len ; i ++)          {             Int v = math.max (Math.min (Leftmax[i], rightmax[i])  - a[i] , 0);             result += v;         }        return result;    }} 


[Leetcode]42 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.