hi, let Avik connect you.
** You can give your thought about this content and request modifications if needed from Ask For Modifications page. Thank You.
** You can check all the posts on the Posts page.
** More about me in the About Me section.
Watering Plants / Watering Flowers
Problem: 2079. Watering Plants / Watering Flowers
Problem Link:
Companies Asked: Google
Approach:
Traverse through the given array flowers.
For ith flower, I have checked if the current amount is lesser than K.
If it is then, increased the steps by 1.
Otherwise, increased the step by 2*i+1. [ 2*i for going to 0th index coming back to ith index. 1 to move to the next step.]
Return total steps.
Time and Space Complexity:
Time Complexity: O(N)
Space Complexity: O(1)
Code [C++]
int totalSteps(int n, int k, vector<int> &flowers) {
int steps = 1, M = k;
k -= flowers[0];
for(int i=1; i<n; i++){
if(flowers[i] <= k){
k -= flowers[i];
steps++;
}
else{
k = M;
k -= flowers[i];
steps += 2 * i + 1;
}
}
return steps;
}