C++ 中陣列移除操作:移除時間大於等於等待時間時的最大移除數


在這個問題中,我們給定了一個包含 N 個元素的陣列。我們的任務是找到當移除時間 >= 等待時間時,陣列中可以移除的最大元素個數。

因此,我們將從陣列中移除元素。陣列元素的值表示移除時間(從陣列中移除元素所需的時間)。

每個元素都有一個等待時間,即它需要等待多長時間才能被移除。

只有當移除時間大於等於等待時間時,才能從陣列中移除元素。

我們需要找到可以從陣列中移除的最大元素個數。可以根據需要更改陣列中元素的順序。

讓我們透過一個例子來理解這個問題:

**輸入** - 陣列 = {12, 3, 11, 7, 5}

**輸出** - 2

**解釋** -

首先,我們將陣列重新排序為升序 -

陣列將變為 {3, 5, 7, 11, 12}

現在,我們將依次移除元素

**移除 3** - 等待時間為 0,小於移除時間 (3)。可以移除。

**移除 5** - 等待時間為 3,小於移除時間 (5)。可以移除。

**移除 7** - 等待時間為 8,大於移除時間 (7)。無法移除。

為了解決這個問題,我們將對陣列進行排序,然後逐個檢查要移除的元素。

演算法

Step 1: Sort the array in ascending order.
Step 2: For every element in the array, Do:
Step 3: Find waiting Time (sum of removal time of all elements before the element).
Step 4: if (waiting time <= removal time )
   step 4.1: remove the element and increase the remove count.
Step 5: else: break.
Step 6: print the number of elements removed.

示例

C++ 程式:查詢移除時間大於等於等待時間時陣列中的最大移除數

 線上演示

#include <bits/stdc++.h>
using namespace std;
int countRemovedElements(int arr[], int n){
   sort(arr, arr + n);
   int removeCount = 0;
   int waitTime = 0;
   for (int i = 0; i < n; i++) {
      if (arr[i] >= waitTime) {
         removeCount++;
         waitTime += arr[i];
      }
      else
         break;
   }
   return removeCount;
}
int main(){
   int arr[] = { 12, 3, 11, 7 , 5 };
   int n = sizeof(arr) / sizeof(arr[0]);
   cout<<"The maximum number of elements that can be removed from the array is "<<countRemovedElements(arr, n);
   return 0;
}

輸出

The maximum number of elements that can be removed from the array is 2

更新於: 2020年6月3日

73 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告