我的代码
// 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;
}
}