This inference problem has many names, including change points, switch points, break points, broken line regression, broken stick regression, bilinear regression, piecewise linear regression, local linear regression, segmented regression, and discontinuity models.
Here is an overview of change point packages with pros/cons and worked examples. If you know the number of change points a priori, check out the mcp package. First, let's simulate the data:
df = data.frame(x = seq(1, 12, by = 0.1))
df$y = c(rnorm(21, 0, 5), rnorm(80, 180, 5), rnorm(10, 20, 5))
For your first problem, it's three intercept-only segments:
model = list(
y ~ 1, # Intercept
~ 1, # etc...
~ 1
)
library(mcp)
fit = mcp(model, df, par_x = "x")
We can plot the resulting fit:
plot(fit)

Here, the change points are very well defined (narrow). Let's summarise the fit to see their inferred locations (cp_1 and cp_2):
summary(fit)
Family: gaussian(link = 'identity')
Iterations: 9000 from 3 chains.
Segments:
1: y ~ 1
2: y ~ 1 ~ 1
3: y ~ 1 ~ 1
Population-level parameters:
name mean lower upper Rhat n.eff
cp_1 3.05 3.0 3.1 1 6445
cp_2 11.05 11.0 11.1 1 6401
int_1 0.14 -1.9 2.1 1 5979
int_2 179.86 178.8 180.9 1 6659
int_3 22.76 19.8 25.5 1 5906
sigma_1 4.68 4.1 5.3 1 5282
You can do much more complicated models with mcp, including modeling Nth-order autoregression (useful for time series), etc. Disclosure: I am the developer of mcp.