使用C ++将数组中的所有元素设为0的最小操作数。

问题陈述

给定大小为N的数组,每个元素为1或0。任务是计算将所有元素转换为零的最小操作数。一个人可以执行以下操作-

如果元素为1,则可以将其值更改为0,然后-

  • 如果下一个连续元素为1,它将自动转换为0

  • 如果下一个连续元素已经为0,则不会发生任何事情。

If arr[] = {1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 1} then 4

operation are required to make all elements zero

算法

1.If the current element is 1 then increment the count and search for the next 0 as all consecutive 1’s will be automatically converted to 0.

2. Return final count

示例

#include <iostream>

#define SIZE(arr) (sizeof(arr) / sizeof(arr[0]))

using namespace std;

int performMinOperation(int *arr, int n){

   int i, cnt = 0;

   for (i = 0; i < n; ++i) {

      if (arr[i] == 1) {

         int j;

         for (j = i + 1; j < n; ++j) {

            if (arr[j] == 0) {

               break;

            }

         }

         i = j - 1;

         ++cnt;

      }

   }

   return cnt;

}

int main(){

   int arr[] = {1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 1};

   cout << "Minimum required operations = " << performMinOperation(arr, SIZE(arr)) << endl;

   return 0;

}

输出结果

当您编译并执行上述程序时。它生成以下输出-

Minimum required operations = 4

以上是 使用C ++将数组中的所有元素设为0的最小操作数。 的全部内容, 来源链接: utcz.com/z/352523.html

回到顶部