1988coder

755. Pour Water

Feb 26th, 2019
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.48 KB | None | 0 0
  1. // LeetCode URL: https://leetcode.com/problems/pour-water/
  2.  
  3. /**
  4.  * Just follow the rules defined in the problem.
  5.  *
  6.  * Time Complexity: O(V * N)
  7.  *
  8.  * Space Complexity: O(1).
  9.  *
  10.  * If we want to save the original array, then we will create a copy of original
  11.  * array and modify the new array with the resultant heights. Space Complexity
  12.  * will still be O(1).
  13.  *
  14.  * N = Length of the heights array.
  15.  */
  16. class Solution {
  17.     public int[] pourWater(int[] heights, int V, int K) {
  18.         if (heights == null) {
  19.             return new int[0];
  20.         }
  21.  
  22.         int len = heights.length;
  23.         if (len == 0 || K < 0 || V == 0 || K >= len) {
  24.             return heights;
  25.         }
  26.  
  27.         while (V > 0) {
  28.             int index = K;
  29.             for (int i = K - 1; i >= 0; i--) {
  30.                 if (heights[i] > heights[index]) {
  31.                     break;
  32.                 }
  33.                 if (heights[i] < heights[index]) {
  34.                     index = i;
  35.                 }
  36.             }
  37.  
  38.             if (index != K) {
  39.                 heights[index]++;
  40.                 V--;
  41.                 continue;
  42.             }
  43.  
  44.             for (int i = K + 1; i < len; i++) {
  45.                 if (heights[i] > heights[index]) {
  46.                     break;
  47.                 }
  48.                 if (heights[i] < heights[index]) {
  49.                     index = i;
  50.                 }
  51.             }
  52.             heights[index]++;
  53.             V--;
  54.         }
  55.  
  56.         return heights;
  57.     }
  58. }
Add Comment
Please, Sign In to add comment