You are given an array of length and can perform the following operation on the array:
- Select a subarray from an array A having the same value of elements and decrease the value of all the elements in that subarray by any positive integer x .
Find the minimum number of operations required to make all the elements of the array A 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[] = { 2, 2, 1, 3, 1 };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 n, vector<int> arr){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<int> arr = {2, 2, 1, 3, 1};cout << minimumOperations(n, arr) << "\n";return 0;}
No comments:
Post a Comment