Height Checker

Students are asked to stand in non-decreasing order of heights for an annual photo.
Return the minimum number of students that must move in order for all students to be standing in non-decreasing order of height.
Notice that when a group of students is selected they can reorder in any possible way between themselves and the non selected students remain in their seats.

Example 1:

Input: heights = [1,1,4,2,1,3]
Output: 3

Approach

Java


import java.util.Arrays;

public class HeightChecker {
    public static void main(String[] args) {
        int[] heights = { 114213 };
        System.out.println(heightChecker(heights));
    }

    static int heightChecker(int[] heights) {
        int[] a = Arrays.copyOf(heights,heights.length);
        int cnt = 0;
        // sort the array
        Arrays.sort(a);
        for (int i = 0; i < a.length; i++)
            if (a[i] != heights[i])
                cnt++;
        return cnt;
    }

}

C++

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

int heightChecker(vector<int&heights)
{
    vector<inta;
    a = heights;
    int cnt = 0;

    //sort the array
    sort(a.begin(), a.end());
    for (int i = 0i < a.size(); i++)
        if (a[i] != heights[i])
            cnt++;
    return cnt;
}

int main()
{
    vector<intheights = {114213};
    cout << heightChecker(heights);
    return 0;
}


No comments:

Post a Comment