# 谷歌OA新变种-浇花2.0

``````// you can also use imports, for example:
// import java.util.*;

// you can write to stdout for debugging purposes, e.g.
// System.out.println("this is a debug message");

class Solution {
public int solution(int[] plants, int capacity1, int capacity2) {
// write your code in Java SE 8
if(plants == null || plants.length == 0){
return 0;
}
//To handle the case when there is exactly one plant with capacity = one of the two can's capacity
if(plants.length==1 && (plants[0] <= Math.max(capacity1, capacity1))){
return 1;
}

//Water first half of the plants
int count =2;
int water_cap = capacity1;
for(int i =0;i<plants.length/2;i++){

//water when possible
if(water_cap >= plants[i])
water_cap -= plants[i];
else{
//increase the count and refill the can
count++;
water_cap = capacity1;
water_cap -= plants[i];

}
}

//Water second half of the plants
int water_cap2 = capacity2;
int x = plants.length/2;
if(plants.length%2==0){
x = (plants.length/2)-1;
}
for(int i =plants.length-1;i>x;i--){

//water when possible
if(water_cap2 >= plants[i])
water_cap2 -= plants[i];
else{
//increase the count and refill the can
count++;
water_cap2 = capacity2;
water_cap2 -= plants[i];

}
}

//To check the middle flower
if(plants.length%2 == 1){
if(water_cap + water_cap2<plants[plants.length/2]){
count++;
}
}

return count;
}
}

``````
``````public int waterPlants(int[] plants, int cap1, int cap2) {
// input validation not needed

int can1 = 0;
int can2 = 0;
int lo = 0;
int hi = plants.length - 1;
int numRefils = 0;

while (lo < hi) {
if (can1 < plants[lo]) {
can1 = cap1;
++numRefils;
}
if (can2 < plants[hi]) {
can2 = cap2;
++numRefils;
}

can1 -= plants[lo++];
can2 -= plants[hi--];
}

if (lo == hi && (plants[lo] > can1 + can2)) {
return ++numRefils;
} else {
return numRefils;
}
}
``````
1 Like