Showing posts with label Sorting. Show all posts
Showing posts with label Sorting. Show all posts

Find Greatest Common Divisor of Array

Given an integer array, nums return the greatest common divisor of the smallest number and the largest number in nums

The greatest common divisor of two numbers is the largest positive integer that evenly divides both numbers.

Example 1:

Input: nums = [2,5,6,9,10]
Output: 2
Explanation:
The smallest number in nums is 2.
The largest number in nums is 10.
The greatest common divisor of 2 and 10 is 2.

Example 2:

Input: nums = [7,5,6,8,3]
Output: 1
Explanation:
The smallest number in nums is 3.
The largest number in nums is 8.
The greatest common divisor of 3 and 8 is 1.


Approach 1:

Using Sorting (min element will be the first element and max element will be the last element).

Time Complexity: O(Nlog(N))

Java

import java.util.Arrays;

public class GCDArrayUsingSorting {
    public static void main(String[] args) {

        int[] nums = { 256910 };

        System.out.println(findGCD(nums));

    }

    static int gcd(int aint b) {
        if (b == 0)
            return a;
        return gcd(b, a % b);
    }

    static int findGCD(int[] nums) {

        Arrays.sort(nums);
        int minElement = nums[0], maxElement = 
nums[nums.length - 1];

        return gcd(minElement, maxElement);
    }

}

C++

#include <bits/stdc++.h>
using namespace std;

int gcd(int aint b)
{
    if (b == 0)
        return a;
    return gcd(ba % b);
}
int findGCD(vector<int&nums)
{

    sort(nums.begin(), nums.end());
    int minElement = nums[0]maxElement = nums[nums.size() - 1];

    return gcd(minElementmaxElement);
}

int main()
{
    vector<intnums = {256910};

    cout << findGCD(nums<< "\n";

    return 0;
}


Approach 2: 

Find minimum element and maximum element by iterating through all elements of the array.

Time Complexity: O(N)

Java

public class GCDArray {
    public static void main(String[] args) {
        int[] nums = { 256910 };

        System.out.println(findGCD(nums));

    }

    static int gcd(int aint b) {
        if (b == 0)
            return a;
        return gcd(b, a % b);
    }

    static int findGCD(int[] nums) {

        int minElement = nums[0], maxElement = nums[0];

        for (int i = 1; i < nums.length; i++) {
            minElement = Math.min(minElement, nums[i]);
            maxElement = Math.max(maxElement, nums[i]);
        }

        return gcd(minElement, maxElement);
    }

}

C++

#include <bits/stdc++.h>
using namespace std;

int gcd(int aint b)
{
    if (b == 0)
        return a;
    return gcd(ba % b);
}
int findGCD(vector<int&nums)
{

    int minElement = nums[0]maxElement = nums[0];

    for (int i = 1i < nums.size(); i++)
    {
        minElement = min(minElementnums[i]);
        maxElement = max(maxElementnums[i]);
    }

    return gcd(minElementmaxElement);
}

int main()
{
    vector<intnums = {256910};

    cout << findGCD(nums<< "\n";

    return 0;
}


Missing Soldiers

An infinite army of ants is marching on an infinite 2-D plane. Since ants are disciplined, here's how they march: each ant chooses exactly one x coordinate and moves along it in positive y-direction, starting from (x, 0). There exists exactly one ant for each x coordinate on that plane and hence there are infinite ants!

There are N horizontal barriers lying on this plane. The ith barrier is defined by (xi, yi) and di, which means that the barrier is blocking all ants which want to pass through points lying on line segment connecting (xi, yi) and (xi + di, yi). Once an ant encounters a barrier, it stops moving.

Given all the barriers, your task is to find the total number of ants, that will be ever blocked at some point in their march.

Example:

Input: n = 2, arr = {{1, 1, 4}, {7, 3, 5}}
Output: 11

Approach

C++

#include <bits/stdc++.h>
using namespace std;

vector<pair<intint>> a;

vector<pair<intint>> merge(const vector<pair<intint>> &x)
{
    int n = x.size();

    //if size is 1 then return the
    //same vector
    if (n == 1)
        return x;
    vector<pair<intint>> res;
    res.push_back(x[0]);
    for (int i = 1i < n; ++i)
    {
        if (x[i].first <= res.back().second)
        {
            res.back().second = max(res.back().second
x[i].second);
        }
        else
        {
            res.push_back(x[i]);
        }
    }
    return res;
}

int missingSoldiers(int nvector<vector<int>> &arr)
{
    int ans = 0;
    for (int i = 0i < ni++)
    {
        a.push_back(make_pair(arr[i][0]arr[i][0] + arr[i][2]));
    }
    //sort the array
    sort(a.begin(), a.end());
    a = merge(a);
    for (int i = 0i < a.size(); ++i)
    {
        ans += (a[i].second - a[i].first + 1LL);
    }
    return ans;
}
int main()
{

    int n = 2;

    vector<vector<int>> arr = {{114},
                               {735}};

    cout << missingSoldiers(narr<< "\n";
    return 0;
}


Eliminate Maximum Number of Monsters

You are playing a video game where you are defending your city from a group of n monsters. You are given a 0-indexed integer array dist of size n, where dist[i] is the initial distance in meters of the ith monster from the city.

The monsters walk toward the city at a constant speed. The speed of each monster is given to you in an integer array speed of size n, where speed[i] is the speed of the ith monster in meters per minute.

The monsters start moving at minute 0. You have a weapon that you can choose to use at the start of every minute, including minute 0. You cannot use the weapon in the middle of a minute. The weapon can eliminate any monster that is still alive. You lose when any monster reaches your city. If a monster reaches the city exactly at the start of a minute, it counts as a loss, and the game ends before you can use your weapon in that minute.

Return the maximum number of monsters that you can eliminate before you lose, or n if you can eliminate all the monsters before they reach the city.

Example 1:

Input: dist = [1,3,4], speed = [1,1,1]
Output: 3
Explanation:
At the start of minute 0, the distances of the monsters are [1,3,4], you eliminate the first monster.
At the start of minute 1, the distances of the monsters are [X,2,3], you don't do anything.
At the start of minute 2, the distances of the monsters are [X,1,2], you eliminate the second monster.
At the start of minute 3, the distances of the monsters are [X,X,1], you eliminate the third monster.
All 3 monsters can be eliminated.

Example 2:

Input: dist = [1,1,2,3], speed = [1,1,1,1]
Output: 1
Explanation:
At the start of minute 0, the distances of the monsters are [1,1,2,3], you eliminate the first monster.
At the start of minute 1, the distances of the monsters are [X,0,1,2], so you lose.
You can only eliminate 1 monster.

Example 3:

Input: dist = [3,2,4], speed = [5,3,2]
Output: 1
Explanation:
At the start of minute 0, the distances of the monsters are [3,2,4], you eliminate the first monster.
At the start of minute 1, the distances of the monsters are [X,0,2], so you lose.
You can only eliminate 1 monster.

Approach

C++

#include <bits/stdc++.h>
using namespace std;

int eliminateMaximum(vector<int&distvector<int&speed)
{
    for (int i = 0i < dist.size(); i++)
    {
        dist[i] = (dist[i] - 1) / speed[i];
    }
    sort(dist.begin(), dist.end());

    for (int i = 0i < dist.size(); i++)
    {
        if (i > dist[i])
            return i;
    }
    return dist.size();
}

int main()
{
    vector<intdist = {134}, speed = {111};

    cout << eliminateMaximum(distspeed<< "\n";

    return 0;
}


Maximum Product Difference Between Two Pairs

The product difference between two pairs (a, b) and (c, d) is defined as (a * b) - (c * d).

  • For example, the product difference between (5, 6) and (2, 7) is (5 * 6) - (2 * 7) = 16.

Given an integer array nums, choose four distinct indices wxy, and z such that the product difference between pairs (nums[w], nums[x]) and (nums[y], nums[z]) is maximized.

Return the maximum such product difference.

Example:

Input: nums = [5,6,2,7,4]
Output: 34
Explanation: We can choose indices 1 and 3 for the first pair (6, 7) and indices 2 and 4 for the second pair (2, 4).
The product difference is (6 * 7) - (2 * 4) = 34.

Approach

C++

#include <bits/stdc++.h>
using namespace std;

int maxProductDifference(vector<int&nums)
{

    //sort the array
    sort(nums.begin(), nums.end());

    //size of array
    int n = nums.size();

    //result will be the difference
    //of product of largest two elements
    //product of smallest two elements
    return (nums[n - 1] * nums[n - 2] - nums[0] * nums[1]);
}
int main()
{
    vector<intnums = {56274};

    cout << maxProductDifference(nums<< "\n";

    return 0;
}


Almost Sorted

Given an array of integers, determine whether the array can be sorted in ascending order using only one of the following operations one time.

  1. Swap two elements.
  2. Reverse one sub-segment.

Determine whether one, both or neither of the operations will complete the task. Output is as follows.

  1. If the array is already sorted, output yes on the first line. You do not need to output anything else.

  2. If you can sort this array using one single operation (from the two permitted operations) then output yes on the first line and then:

    • If elements can only be swapped,  and , output swap l r in the second line.  and  are the indices of the elements to be swapped, assuming that the array is indexed from  to .
    • If elements can only be reversed, for the segment , output reverse l r in the second line.  and  are the indices of the first and last elements of the subarray to be reversed, assuming that the array is indexed from  to . Here  represents the subarray that begins at index  and ends at index , both inclusive.

If an array can be sorted both ways, by using either swap or reverse, choose swap.

  1. If the array cannot be sorted, either way, output no on the first line.

Example:

Input:  n = 6, arr = {1, 5, 4, 3, 2, 6}

Output:

yes reverse 2 5

Approach:

C++

#include <bits/stdc++.h>
using namespace std;

void almostSorted(vector<intarr)
{
    //if the array is already sorted
    //then print yes
    if (is_sorted(arr.begin(), arr.end()))
    {
        cout << "yes";
        return;
    }
    int firstlast;

    //find the firts element which is not
    //in the increasing order
    for (int i = 0i < arr.size() - 1i++)
        if (arr[i] > arr[i + 1])
        {
            first = i;
            break;
        }
    //similarly find the last element
    //which is not in proper sequence
    for (int i = arr.size() - 1i > 0i--)
        if (arr[i - 1] > arr[i])
        {
            last = i;
            break;
        }

    //swap both the elements
    swap(arr[first]arr[last]);

    //if array is sorted then print yes
    //and position of swapped element
    if (is_sorted(arr.begin(), arr.end()))
    {
        cout << "yes" << endl
             << "swap " << first + 1 << " " << last + 1;
        return;
    }

    //if not sorted then again swap
    //previously swappped element to get
    //back into the orginal array
    swap(arr[first]arr[last]);

    //reverse array from position first to last
    reverse(arr.begin() + firstarr.begin() + last + 1);

    //if array is sorted then print yes and
    // reverse positions
    if (is_sorted(arr.begin(), arr.end()))
    {
        cout << "yes" << endl
             << "reverse " << first + 1 << " " << last + 1;
        return;
    }

    //otherwise not possible to make array sorted by
    //these operations
    cout << "no";
}

int main()
{

    int n = 6;
    vector<intarr = {154326};
    almostSorted(arr);

    return 0;
}