Exercises on codility (14)

Source: Internet
Author: User

(1) Tieropes

Given n-segment rope--a positive integer array, and a positive integer k, can only connect adjacent two ropes at a time, connect the length of the rope to the length of the rope before, and the position is unchanged, asked so connected, up to how many root length of at least k rope?

Data range: n[1..10^5], array elements and K range [1..10^9].

Complexity required: Time O (N), Space O (1).

Analysis: Assuming that a rope is eventually thrown away, why not attach the rope to its adjacent rope? So I won't throw the rope ... So the linear sweep sum >= k is a ...

You can also with 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 segments, each segment is [A[i],b[i]] (closed interval), and the line segment has been sorted by the end endpoint to find out how many segments with no common points can be selected.

Data range N [0..30000], A, b arrays are integers, range [0..10^9].

Complexity of requirements: the time space is O (1).

Analysis: This is the event scheduling problem ... And the interval is sorted by the right endpoint, greedy one by one, the intersection will be thrown away.


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;}

Exercises on codility (14)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.