Exercises on Codility (14) and exercises on codility 14
(1) TieRopes
Given n segments of rope-an array of positive integers and a positive integer K, only two adjacent Ropes can be connected at a time. The length of the rope is the same as the length of the previous rope and the position remains unchanged, how many ropes with at least K length can be formed after such a connection?
Data range: N [1 .. 10 ^ 5], range of array elements and K [1 .. 10 ^ 9].
Complexity required: time O (N), Space O (1 ).
Analysis: If a rope is finally thrown away, why not connect it to its adjacent rope? So I won't throw a rope ...... So the sum of a linear sweep> = K is one...
// you can also use includes, for example:// #include <algorithm>int solution(int K, vector<int> &A) { // write your code in C++11 int r = 0; for (int i = 0; i < A.size();) { int length = 0; for (; (i < A.size()) && (length < K); length += A[i++]) ; if (length >= K) { ++r; } } return r; }
(2) MaxNonoverlappingSegments
Given N line segments, each line segment is in the form of [A [I], B [I] (closed interval). The line segments are sorted by the end endpoint, find the maximum number of lines without public points that can be selected.
The data range is N [0 .. 30000]. arrays A and B are all integers in the range of [0 .. 10 ^ 9].
Complexity required: the time space is O (1 ).
Analysis: this is the issue of activity arrangement ...... In addition, the intervals are sorted by the right endpoint. If you want to obtain them one by one, the intersection will be discarded.
Code:
// you can use includes, for example:// #include <algorithm>// you can write to stdout for debugging purposes, e.g.// cout << "this is a debug message" << endl;int solution(vector<int> &A, vector<int> &B) { // write your code in C++11 int last = -1, answer = 0; for (int i = 0; i < A.size(); ++i) { if ((last < 0) || (A[i] > B[last])) { last = i; ++answer; } } return answer;}