令 ans 為最大的區間和,則可以枚舉每個區間 [i,i+minutes−1] 並計算區間和,最後返回 tot+ans 即可。
複雜度分析
時間複雜度:O(n) 。
空間複雜度:O(n) 。
1 2 3 4 5 6 7 8 9 10 11
classSolution: defmaxSatisfied(self, customers: List[int], grumpy: List[int], minutes: int) -> int: n = len(customers) tot = sum(customers[i] for i inrange(n) ifnot grumpy[i]) s = [0] * (n+1) for i inrange(n): s[i+1] = s[i] + customers[i] * grumpy[i] ans = 0 for i inrange(n - minutes + 1): ans = max(ans, s[i+minutes] - s[i]) return tot + ans
1 2 3 4 5 6 7 8 9 10 11 12 13 14
classSolution { public: intmaxSatisfied(vector<int>& customers, vector<int>& grumpy, int minutes){ int n = customers.size(), tot = 0, ans = 0; vector<int> s(n + 1); // prefix sum for (int i = 0; i < n; i++) { s[i + 1] = s[i] + customers[i] * grumpy[i]; tot += customers[i] * (1 ^ grumpy[i]); } for (int i = 0; i <= (n - minutes); i++) ans = max(ans, s[i + minutes] - s[i]); return tot + ans; } };
方法二:滑動窗口(Sliding Window)
對於每一分鐘,若該分鐘老闆心情本來就是好的,則不用考慮是否需要使用秘訣。因此可以先計算在老闆心情好時的顧客數量 tot 。如此便只需要考慮老闆心情不好的時刻即可。
令 cur 紀錄當前窗口內,在老闆不開心的情況下的顧客數量、ans 表示最大的窗口值。則可以將 cur 初始化為前 minutes 分鐘老闆不開心時的顧客數量總和。之後從 minutes 分鐘開始遍歷,每次更新 cur 為 cur+customers[i]×grumpy[i]−customers[i−minutes]×grumpy[i−minutes],即加上當前分鐘的顧客數量,減去窗口左側的顧客數量。最後返回 tot+ans 即可。
複雜度分析
時間複雜度:O(n) 。
空間複雜度:O(1) 。
1 2 3 4 5 6 7 8 9
classSolution: defmaxSatisfied(self, customers: List[int], grumpy: List[int], minutes: int) -> int: n = len(customers) tot = sum(customers[i] for i inrange(n) ifnot grumpy[i]) ans = cur = sum(customers[i] * grumpy[i] for i inrange(minutes)) for i inrange(minutes, n): cur += customers[i] * grumpy[i] - customers[i - minutes] * grumpy[i - minutes] ans = max(ans, cur) return tot + ans
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
classSolution { public: intmaxSatisfied(vector<int>& customers, vector<int>& grumpy, int minutes){ int n = customers.size(), tot = 0, cur = 0; for (int i = 0; i < n; i++) tot += customers[i] * (1 ^ grumpy[i]); for (int i = 0; i < minutes; i++) cur += customers[i] * grumpy[i]; int ans = cur; for (int i = minutes; i < n; i++) { cur += customers[i] * grumpy[i] - customers[i - minutes] * grumpy[i - minutes]; ans = max(ans, cur); } return tot + ans; } };
寫在最後
Cover photo is generated by @たろたろ, thanks for their work!