Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // LeetCode URL: https://leetcode.com/problems/pour-water/
- /**
- * Just follow the rules defined in the problem.
- *
- * Time Complexity: O(V * N)
- *
- * Space Complexity: O(1).
- *
- * If we want to save the original array, then we will create a copy of original
- * array and modify the new array with the resultant heights. Space Complexity
- * will still be O(1).
- *
- * N = Length of the heights array.
- */
- class Solution {
- public int[] pourWater(int[] heights, int V, int K) {
- if (heights == null) {
- return new int[0];
- }
- int len = heights.length;
- if (len == 0 || K < 0 || V == 0 || K >= len) {
- return heights;
- }
- while (V > 0) {
- int index = K;
- for (int i = K - 1; i >= 0; i--) {
- if (heights[i] > heights[index]) {
- break;
- }
- if (heights[i] < heights[index]) {
- index = i;
- }
- }
- if (index != K) {
- heights[index]++;
- V--;
- continue;
- }
- for (int i = K + 1; i < len; i++) {
- if (heights[i] > heights[index]) {
- break;
- }
- if (heights[i] < heights[index]) {
- index = i;
- }
- }
- heights[index]++;
- V--;
- }
- return heights;
- }
- }
Add Comment
Please, Sign In to add comment