Showing posts with label Greedy. Show all posts
Showing posts with label Greedy. Show all posts

Wednesday, April 5, 2017

Queue Reconstruction by Height -- LeetCode

[Question]
Suppose you have a random list of people standing in a queue. Each person is described by a pair of integers (h, k), where h is the height of the person and k is the number of people in front of this person who have a height greater than or equal to h. Write an algorithm to reconstruct the queue.
Note:
The number of people is less than 1,100.
Example
Input:
[[7,0], [4,4], [7,1], [5,0], [6,1], [5,2]]

Output:
[[5,0], [7,0], [5,2], [6,1], [4,4], [7,1]]

[Analysis]
Be Greedy. Person (h,k) at position 0 should have k=0. So group all (h,0), the one with smallest h' is at position 0. Then look at all other persons (h,k) whose h is greater or equal to h', decrease their k by 1 (because h' contribute 1 to their k values). Repeat the previous steps and find person at position 1, .., n. The time complexity is O(N^2).

Another way to reconstruct the queue is by sorting. Suppose a person (h',k'), all persons (h,k) with greater or equal height have been in a sorted queue Q, the k' is the right position to insert (h',k') into the Q and create a Q' while maintaining all existing (h,k). Repeat the same process on Q' and remaining persons. The time complexity is O(N^2).

[Solution]
//-- using sorting --
class Solution {
public:
    vector<pair<int, int>> reconstructQueue(vector<pair<int, int>>& people) {
        auto comp=[](pair<int,int> &a, pair<int,int> &b)
            { return a.first<b.first || a.first==b.first && a.second > b.second;};
        sort (people.begin(), people.end(), comp);
        vector<int,int> res;
        for (int i=people.size(); i>=0; i++)
            res.(res.begin()+people[i].second, people[i]);
    }
};

//--greedy --
class Solution {
public:
    vector<pair<int, int>> reconstructQueue(vector<pair<int, int>>& people) {
        vector<pair<int, int>> rslt;
     
        vector<pair<int, int>> bak (people);
        auto comp= [](pair<int, int> a, pair<int,int> b)
            { return a.second < b.second || a.second ==b.second && a.first<b.first;};
         
        while (rslt.size()!= people.size() ) {
            auto it = min_element(bak.begin(), bak.end(), comp);
            rslt.push_back(people[it-bak.begin()] );
            it->second = INT_MAX;
            for (auto &p: bak) {
                if (p.second!=INT_MAX && p.first<=it->first) {
                    p.second --;
                }
            }
        }
        return rslt;
    }
};

Saturday, November 12, 2016

Meeting Room II -- LeetCode

[Question]
Given an array of meeting time intervals consisting of start and end times [[s1,e1],[s2,e2],...] (si < ei), find the minimum number of conference rooms required.
For example, Given [[0, 30],[5, 10],[15, 20]], return 2.
[Analysis]
This is another interval related problem. First, we can sort all the starts (s1, s2, ...) and ends (e1, e2, ...) into two series. Then, for each ends 'e', count how many starts are before 'e' -- that is how many rooms we need before time 'e'. Time complexity is O(N Log N), space complexity is O(N).

The similar problems: "Non-overlapping Intervals", "Minimum Number of Arrows to Burst Balloons".

[Solution]
public class Solution {
    public int minMeetingRooms(vector<Interval> intervals) {
        vector<int> starts(intervals.size(), 0);
        vector<int> ends(intervals.size(), 0);
        for (int i=0; i<intervals.size(); i++) {
            starts[i] = intervals[i].start;
            ends[i] = intervals[i].end;
        }
        sort (starts.begin(), starts.end());
        sort(ends.begin(), ends.end());
        int room=0; int j=0;
        int res =0;
        for (auto e: ends) {
            while (starts[j]<e) {
                j++; room++;
                res = max(res, room);
            }
            room--;
         }
         return res;
    }
}

//
// Using Hash Table
//
class Solution {
public:
    int minMeetingRooms(vector<Interval>& intervals) {
        map<int, int> m;
        for (auto a : intervals) {
            m[a.start]++;
            m[a.end]--;
        }
        int rooms = 0, res = 0;
        for (auto it : m) {
            res = max(res, rooms += it.second);
        }
        return res;
    }
};

Non-overlapping Intervals -- LeetCode 435

[Question]
Given a collection of intervals, find the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping.
Note:
  1. You may assume the interval's end point is always bigger than its start point.
  2. Intervals like [1,2] and [2,3] have borders "touching" but they don't overlap each other.
Example 1:
Input: [ [1,2], [2,3], [3,4], [1,3] ]

Output: 1

Explanation: [1,3] can be removed and the rest of intervals are non-overlapping.
Example 2:
Input: [ [1,2], [1,2], [1,2] ]

Output: 2

Explanation: You need to remove two [1,2] to make the rest of intervals non-overlapping.
Example 3:
Input: [ [1,2], [2,3] ]

Output: 0

Explanation: You don't need to remove any of the intervals since they're already non-overlapping.
[Analysis]
This problem is equivalent to the problem "Minimum Number of Arrows to Burst Balloons". Instead of counting the overlapping intervals, this problem needs to calculate the number of redundant intervals.

The basic idea is to use a greedy approach. 1) sort the intervals by the ends; 2) suppose we have a few selected non-overlapping intervals, use the end of  the last interval X as a vertical scan line from left to right: any intervals with start that is smaller than the scan line will be overlapped with X, therefore, place the first non-overlapping interval X1 into selected list and repeat 2).

[Solution]
class Solution {
public:
    int eraseOverlapIntervals(vector<Interval>& intervals) {
        auto comp = [](Interval a, Interval b) { return a.end==b.end && a.start<b.start|| a.end<b.end;};
        sort(intervals.begin(), intervals.end(), comp);
     
        int count=0, line = INT_MIN;
        for(auto& e: intervals) {
            if (e.start< line ) continue;
            count++;
            line = e.end;
        }
        return intervals.size()-count;
    }
};

Friday, November 11, 2016

Minimum Number of Arrows to Burst Balloons -- LeetCode

[Question]
There are a number of spherical balloons spread in two-dimensional space. For each balloon, provided input is the start and end coordinates of the horizontal diameter. Since it's horizontal, y-coordinates don't matter and hence the x-coordinates of start and end of the diameter suffice. Start is always smaller than end. There will be at most 104 balloons.
An arrow can be shot up exactly vertically from different points along the x-axis. A balloon with xstart and xend bursts by an arrow shot at x if xstart ≤ x ≤ xend. There is no limit to the number of arrows that can be shot. An arrow once shot keeps travelling up infinitely. The problem is to find the minimum number of arrows that must be shot to burst all balloons.
Example:
Input:
[[10,16], [2,8], [1,6], [7,12]]

Output:
2

Explanation:
One way is to shoot one arrow for example at x = 6 (bursting the balloons [2,8] and [1,6]) and another arrow at x = 11 (bursting the other two balloons).
[Analysis]
First, sort the balloons by the end of their end of the diameter suffice.  Then, using those ends as the positions to shot the arrow and all those balloons whose 'start'  <=  'the current arrow position', will burst. The time complexity is O(N LogN) due to sorting, the space complexity is O(1).

[Solution]
class Solution {
public:
    int findMinArrowShots(vector<pair<int, int>>& points) {
        if (points.size()<2) return points.size();
       
        #define PT pair<int,int>        
        auto comp = [](PT& a, PT& b) { return (a.second==b.second)?a.first<b.first: a.second<b.second; };
        sort(points.begin(), points.end(), comp);
       
        int count=0, arrow=INT_MIN;
        for (auto& p:points) {
            if (p.first<=arrow) continue;
            count++, arrow=p.second;
        }
        return count;
    }
};

Sunday, May 27, 2012

Jump Game (2)

[Question]
Given an array of non-negative integers, you are initially positioned at the first index of the array.

Each element in the array represents your maximum jump length at that position.

Your goal is to reach the last index in the minimum number of jumps.

For example:
Given array A = [2,3,1,1,4]

The minimum number of jumps to reach the last index is 2. (Jump 1 step from index 0 to 1, then 3 steps to the last index.)

[Analysis]
Be greedy. Assume the minimum steps to reach position i is S[i], then from position i+1 to A[i]+i, the steps to reach are at most S[i]+1 (part of [ i+1, A[i]+i ] may already be reached before using A[i]).

[Solution]
//-----------
//-- C++ --
//-----------
class Solution {
public:
    int jump(vector<int>& nums) {
        int n=nums.size();
        vector<int> cnt(n,0);

        for (int i=0, k=0; i<n && k<n; i++)
            for(int j=k; j<min(n, nums[i]+i+1); j++,k++)
                cnt[j] = (i==j)?0:cnt[i]+1;
               
        return cnt.back();
    }
};

Saturday, May 26, 2012

Jump Game (1)

[Question]
Assume an array of integers, A[i]>=0, represents the maximum steps allowed to move forward from i. Starting scan from A[0], is there a path to reach the end of A (i.e. A[n-1])?

For example, given {3, 0, 2, 1, 2, 0, 0}, there is a path A[0], A[3], A[4], A[6]; given {3, 0, 2, 0, 2, 0, 0}, the path has to be A[0], A[2], A[4], A[6]; given {3, 1, 1, 0, 2, 0, 0},  no path to the end.

[Analysis]
Be greedy. Push the reach from the A[0] to forward index  j ="A[0]+0", A[1] to index j = max(j, A[1]+1), until i> j (unreachable anymore), or forward index j covers A's last index.

[Solution]
class Solution {
public:
    bool canJump(vector<int>& nums) {
        int i=0, j=0;
        while (i<=j) {
            j = max(j, nums[i]+i);
            if (j>=nums.size()-1)
                return true;
            i++;
        }
        return false;
    }
};

Tuesday, April 17, 2012

Container With Most Water


[Question]:
Given n non-negative integers a1a2, ..., an, where each represents a point at coordinate (iai). n vertical lines are drawn such that the two endpoints of line i is at (iai) and (i, 0). Find two lines, which together with x-axis form a container, such that the container contains the most water.
Note: You may not slant the container.
[Analysis]:
Area(i,j) = Min(Ai, Aj) * (j-i);
The min of (Ai, Aj) decides the area of the container. For k, i<k<j, Area (i, k) < Area(i, j) if Ai < Aj: i.e. all Area(i,k) can be ruled out.
[Solution]:
public class Solution {
    int maxArea(vector<int>& height) {
        int i=0, j=height.size()-1;
        int ret=0;
        while (i<j) {
            ret = max(ret, min(height[i],height[j]) * (j-i));
            if (height[i]<height[j]) i++;
            else j--;
        }
        return ret;
    }
}