Solution
Flower Growth Simulation — Problem Explanation
We are given an array of length $$$n$$$ that represents whether Petya watered his flower each day.
Each element $$$a_i$$$ is either:
- $$$1$$$ → the flower was watered
- $$$0$$$ → the flower was not watered
The flower begins at a height of $$$1$$$ cm on day 0 (before processing any input days).
Simulation Logic
We iterate through the array starting from index $$$1$$$ (the second day), and at each step, we examine the current element $$$a_i$$$ and the previous element $$$a_{i-1}$$$.
There are four possible scenarios:
- Case 1: $$$a_i = 1$$$ and $$$a_{i-1} = 1$$$
→ The flower was watered both yesterday and today
→ It grows by $$$5$$$ cm
→height += 5
- Case 2: $$$a_i = 1$$$ and $$$a_{i-1} = 0$$$
→ The flower was watered today only
→ It grows by $$$1$$$ cm
→height += 1
- Case 3: $$$a_i = 0$$$ and $$$a_{i-1} = 1$$$
→ The flower was not watered today, but was yesterday
→ It doesn't grow, but remains alive
→heightremains the same
- Case 4: $$$a_i = 0$$$ and $$$a_{i-1} = 0$$$
→ The flower was not watered for two consecutive days
→ The flower dies
→return -1
Initialization
- The simulation starts with:
height = 1
We loop through the array once and apply the above logic. If the flower survives all $$$n$$$ days, we return the final . If it dies due to two unwatered days in a row, we return -1.
Time Complexity
- This approach has a time complexity of $$$O(n)$$$, since we loop through the array once.
Code
t = int(input())
for _ in range(t):
n = int(input())
arr = list(map(int, input().split()))
height = 1
if arr[0] == 1:
height += 1
for i in range(1, n):
if arr[i] == 1 and arr[i - 1] == 1:
height += 5
elif arr[i] == 1 and arr[i - 1] == 0:
height += 1
elif arr[i] == 0 and arr[i - 1] == 0:
height = -1
break
print(height)



