Coding Practice

Write a C Program to check the minimum number of turns required

Check Minimum Number of Turns Required

1. You’re given an array of n integers. You want to modify the array so that it is increasing, i.e., each component is at least as large as the previous component. On every turn, you may increase the worth of any component by one. What's the minimum number of turns required?

Input: The 1st input line contains number n: the size (limit) of the array. Then, the 2nd line contains n integers (the contents of the array).

Output: Print the minimum number of turns.

Sample Input Sample Output
5
3 2 5 1 7
5 turns
4
1 2 2 6
0 turns

Explanation: Total input numbers = 5
Turns = 3 - 2 = 1 turns
Turns = 2 - 5 = 0+1 turns
Turns = 5 - 1 = 4+0+1 turns
Turns = 1 - 7 = 0+4+0+1 turns
So, Total Turns = 5

Sample Output
5
3 2 5 1 7
5 turns


Process returned 0 (0x0)   execution time : 10.196 s
Press any key to continue.
Source Code
#include<stdio.h>
 
int main()
{
    int i, size, turn = 0;
    scanf("%d", &size);
    int numbers[size];
 
    for(i = 0; i < size; i++)
    {
        scanf("%d", &numbers[i]);
    }
 
    for(i = 1; i < size; i++)
    {
        if(numbers[i-1] > numbers[i])
        {
            turn += (numbers[i-1] - numbers[i]);
            //Or, you can also write this line. Both are same.
            //turn = turn + (numbers[i-1] - numbers[i]);
        }
    }
    printf("%d turns\n\n", turn);
 
    return 0;
}
Sample Output
4
1 2 2 6
0 turns


Process returned 0 (0x0)   execution time : 4.518 s
Press any key to continue.

No comments:

Post a Comment

Change Theme
X