简体   繁体   中英

Finding maximum number of time windows in two arrays. StartArray and EndArray

I have two Integer arrays, StartArray and EndArray . StartArray contains time of starting a seminar and EndArray contains corresponding end time. I have a auditorium to rent. I want to find maximum combinations when I can do this.

For example, if I have:

int[] startArray = {5,7,2};
int[] endArray = {10,11,6};

So I can rent my hall from 5 to 10, 7 to 11, 2 to 6. Out of these 3 combination best for me is to go for 2 to 6 and then 7 to 11. Leaving 5 to 10 (as the auditorium is already on rent).

Can anyone please help me with the logic? I have been working on it since hours an I think my head will burst now.

As It's said, the key for the solution is greedy algorithm. More about this algorithm you can read there:

Useful article on WiKi about maximum disjoint sets of objects

One of the possible solutions:

1) Declare a class to represent segments:

class Segment implements Comparable<Segment> {

    int left;
    int right;

    Segment(int left, int right) {
        this.left = left;
        this.right = right;
    }

    @Override
    public int compareTo(Segment segment) {
        return segment.left - left;
    }

    @Override
    public String toString() {
        return "[" + left + "," + right + "]";
    }
}

2) Declare a main class:

import java.util.ArrayList;
import java.util.Collections;

public class MaximumDisjointSet {

    public static void main(String[] args) {
        // List of all segments
        ArrayList<Segment> segments = new ArrayList<>();

        // Add segments
        segments.add(new Segment(5, 10));
        segments.add(new Segment(7, 11));
        segments.add(new Segment(2, 6));

        // Sort all segments by their left endpoint in descending order
        Collections.sort(segments);

        // Store the left endpoint of last accepted segment,
        // initially it's useful to assign it "infinity"
        int lastAcceptedLeftPoint = Integer.MAX_VALUE;

        for (Segment segment : segments) {
            // Accept current segment if it's right endpoint is lesser
            // than the left endpoint of last accepted segment
            if (segment.right < lastAcceptedLeftPoint) {
                lastAcceptedLeftPoint = segment.left;
                System.out.println(segment);
            }
        }
    }
}

The output will be:

[7,11]
[2,6]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM