C++ 程式碼查詢電視觀看一場比賽的時間


假設我們有一個包含 n 個元素的陣列 A。Amal 想觀看一場 90 分鐘的比賽,且沒有任何休息。每分鐘可能是精彩或者無聊。如果連續 15 分鐘是無聊的,則 Amal 會立即關閉電視。陣列 A 中有 n 分鐘精彩比賽。我們需要計算 Amal 觀看比賽的時間。

因此,如果輸入像 A = [7, 20, 88],則輸出將為 35,因為在 20 分鐘後,他仍然會觀看比賽直到 35 分鐘,然後關閉電視。

步驟

要解決此問題,我們將按照以下步驟操作 −

Define an array a of size: 100.
n := size of A
for initialize i := 1, when i <= n, update (increase i by 1), do:
   a[i] := A[i - 1]
   if a[i] - a[i - 1] > 15, then:
      Come out from the loop
return minimum of (a[i - 1] + 15) and 90

例子

讓我們看看以下實現以獲得更好的理解 −

#include <bits/stdc++.h>
using namespace std;
int solve(vector<int> A){
   int i, a[100];
   int n = A.size();
   for (i = 1; i <= n; i++){
      a[i] = A[i - 1];
      if (a[i] - a[i - 1] > 15)
         break;
   }
   return min(a[i - 1] + 15, 90);
}
int main(){
   vector<int> A = { 7, 20, 88 };
   cout << solve(A) << endl;
}

輸入

{ 7, 20, 88 }

輸出

35

更新於:30-Mar-2022

138 次瀏覽

開啟您的 職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.