<script>
function
minSteps(str, n, k)
{
if
(str[n - 1] == '0
')
return -1;
// Already at the end
if (n == 1)
return 0;
// If the length is 2 or 3 then the end
// can be reached in a single step
if (n < 4)
return 1;
// For the other cases, solve the problem
// using dynamic programming
var dp = Array(n);
// It requires no move from the
// end to reach the end
dp[n - 1] = 0;
// From the 2nd last and the 3rd last
// index, only a single move is required
dp[n - 2] = 1;
dp[n - 3] = 1;
// Update the answer for every index
for (var i = n - 4; i >= 0; i--) {
// If the current index is not reachable
if (str[i] == '
0
')
continue;
// To store the minimum steps required
// from the current index
var steps = 1000000000;
// If it is a valid move then update
// the minimum steps required
if (i + k < n && str[i + k] == '
1
')
steps = Math.min(steps, dp[i + k]);
if (str[i + 1] == '
1
')
steps = Math.min(steps, dp[i + 1]);
if (str[i + 2] == '
1')
steps = Math.min(steps, dp[i + 2]);
dp[i] = (steps == 1000000000) ? steps : 1 + steps;
}
if
(dp[0] == 1000000000)
return
-1;
return
dp[0];
}
var
str =
"101000011"
;
var
n = str.length;
var
k = 5;
document.write( minSteps(str, n, k));
</script>