You are given an array of integers. You want to modify the array so that it is increasing, i.e., every element is at least as large as the previous element.
On each move, you may increase the value of any element by one. What is the minimum number of moves required?
Example:
Input: n = 5, arr[n] = {3, 2, 5, 1, 7}
Output: 5
Approach
Java
public class IncreasingArray {public static void main(String[] args) {int n = 5;int arr[] = { 3, 2, 5, 1, 7 };System.out.println(increasingArray(n, arr));}static int increasingArray(int n, int arr[]) {int cnt = 0;for (int i = 1; i < n; i++) {if (arr[i] < arr[i - 1]) {cnt += arr[i - 1] - arr[i];arr[i] = arr[i - 1];}}return cnt;}}
C++
#include <bits/stdc++.h>using namespace std;long long increasingArray(long long n, long long arr[]){long long cnt = 0;for (long long i = 1; i < n; i++){if (arr[i] < arr[i - 1]){cnt += arr[i - 1] - arr[i];arr[i] = arr[i - 1];}}return cnt;}int main(){long long n = 5;long long arr[n] = {3, 2, 5, 1, 7};cout << increasingArray(n, arr);return 0;}
No comments:
Post a Comment