Minimum operations

You are given an array A of length N and can perform the following operation on the array:

  • Select a subarray from an array AA having the same value of elements and decrease the value of all the elements in that subarray by any positive integer x x.

Find the minimum number of operations required to make all the elements of the array AA equal to zero.

Example:

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

Approach

Java


public class MinimumOperations {
    public static void main(String[] args) {
        int N = 5;

        long prev = 0;
        int count = 0;
        int arr[] = { 22131 };

        for (int i = 0; i < N; i++) {
            long current = arr[i];
            if (current != prev) {
                count++;
            }
            prev = current;
        }
        System.out.println(count);
    }
}

  C++

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

int minimumOperations(int nvector<intarr)
{
    int i = 0;

    int cnt = 0;
    while (i < n)
    {

        cnt++;
        while (i < n - 1 && arr[i] == arr[i + 1])
        {
            i++;
        }
        i++;
    }
    return cnt;
}
int main()
{
    int n = 5;

    vector<intarr = {22131};

    cout << minimumOperations(narr<< "\n";

    return 0;
}


No comments:

Post a Comment