Increasing Array

You are given an array of n 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[] = { 32517 };

        System.out.println(increasingArray(n, arr));

    }

    static int increasingArray(int nint 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 nlong long arr[])
{
    long long cnt = 0;
    for (long long i = 1i < ni++)
    {
        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] = {32517};

    cout << increasingArray(narr);

    return 0;
}


No comments:

Post a Comment