
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Minimum Jumps to Reach Home by Frog in C++
Suppose we have one binary string S with n bits and another number d. On a number line, a frog wants to reach point n, starting from the point 1. The frog can jump to the right at a distance not more than d. For each point from 1 to n if there is a lily flower it is marked as 1, and 0 if not. The frog can jump only in points with a lilies. We have to find the minimal number of jumps that the frog needs to reach n. If not possible, return -1.
So, if the input is like S = "10010101"; d = 4, then the output will be 2, because from position 1, it jumps to 4, then at the index 8(n).
Steps
To solve this, we will follow these steps −
n := size of s x := 0 y := 0 while (x < n - 1 and y <= n), do: if s[x] is same as '1', then: x := x + d increase y by 1 Otherwise (decrease x by 1) if y >= n, then: return -1 Otherwise return y
Example
Let us see the following implementation to get better understanding −
#include <bits/stdc++.h> using namespace std; int solve(string s, int d){ int n = s.size(); int x = 0, y = 0; while (x < n - 1 && y <= n){ if (s[x] == '1') x += d, ++y; else --x; } if (y >= n) return -1; else return y; } int main(){ string S = "10010101"; int d = 4; cout << solve(S, d) << endl; }
Input
"10010101", 4
Output
2
Advertisements