The post 花花酱 LeetCode 1125. Smallest Sufficient Team appeared first on Huahua's Tech Road.

]]>In a project, you have a list of required skills `req_skills`

, and a list of `people`

. The i-th person `people[i]`

contains a list of skills that person has.

Consider a *sufficient team*: a set of people such that for every required skill in `req_skills`

, there is at least one person in the team who has that skill. We can represent these teams by the index of each person: for example, `team = [0, 1, 3]`

represents the people with skills `people[0]`

, `people[1]`

, and `people[3]`

.

Return **any** sufficient team of the smallest possible size, represented by the index of each person.

You may return the answer in any order. It is guaranteed an answer exists.

**Example 1:**

Input:req_skills = ["java","nodejs","reactjs"], people = [["java"],["nodejs"],["nodejs","reactjs"]]Output:[0,2]

**Example 2:**

Input:req_skills = ["algorithms","math","java","reactjs","csharp","aws"], people = [["algorithms","math","java"],["algorithms","math","reactjs"],["java","csharp","aws"],["reactjs","csharp"],["csharp","math"],["aws","java"]]Output:[1,2]

**Constraints:**

`1 <= req_skills.length <= 16`

`1 <= people.length <= 60`

`1 <= people[i].length, req_skills[i].length, people[i][j].length <= 16`

- Elements of
`req_skills`

and`people[i]`

are (respectively) distinct. `req_skills[i][j], people[i][j][k]`

are lowercase English letters.- It is guaranteed a sufficient team exists.

**Solution: DP**

// Author: Huahua, 24 ms / 11 MB class Solution { public: vector<int> smallestSufficientTeam(vector<string>& req_skills, vector<vector<string>>& people) { const int n = req_skills.size(); const int target = (1 << n) - 1; vector<int> skills; for (const auto& p : people) { int mask = 0; for (const string& s: p) mask |= (1 << find(begin(req_skills), end(req_skills), s) - begin(req_skills)); skills.push_back(mask); } vector<int> dp((1 << n), INT_MAX / 2); vector<pair<int, int>> pt((1 << n)); dp[0] = 0; for (int i = 0; i < people.size(); ++i) { const int k = skills[i]; if (k == 0) continue; for (int j = target; j >= 0; --j) if (dp[j] + 1 < dp[j | k]) { dp[j | k] = dp[j] + 1; pt[j | k] = {j, i}; } } int t = target; vector<int> ans; while (t) { ans.push_back(pt[t].second); t = pt[t].first; } return ans; } };

// Author: Huahua, 272 ms / 94.8 MB class Solution { public: vector<int> smallestSufficientTeam(vector<string>& req_skills, vector<vector<string>>& people) { const int n = req_skills.size(); vector<int> skills; for (const auto& p : people) { int mask = 0; for (const string& s: p) mask |= (1 << find(begin(req_skills), end(req_skills), s) - begin(req_skills)); skills.push_back(mask); } unordered_map<int, vector<int>> dp; dp[0] = {}; for (int i = 0; i < people.size(); ++i) { unordered_map<int, vector<int>> tmp(dp); for (const auto& kv : dp) { int k = kv.first | skills[i]; if (!tmp.count(k) || kv.second.size() + 1 < tmp[k].size()) { tmp[k] = kv.second; tmp[k].push_back(i); } } tmp.swap(dp); } return dp[(1 << n) - 1]; } };

The post 花花酱 LeetCode 1125. Smallest Sufficient Team appeared first on Huahua's Tech Road.

]]>The post 花花酱 LeetCode 1124. Longest Well-Performing Interval appeared first on Huahua's Tech Road.

]]>We are given `hours`

, a list of the number of hours worked per day for a given employee.

A day is considered to be a *tiring day* if and only if the number of hours worked is (strictly) greater than `8`

.

A *well-performing interval* is an interval of days for which the number of tiring days is strictly larger than the number of non-tiring days.

Return the length of the longest well-performing interval.

**Example 1:**

Input:hours = [9,9,6,0,6,6,9]Output:3Explanation:The longest well-performing interval is [9,9,6].

**Constraints:**

`1 <= hours.length <= 10000`

`0 <= hours[i] <= 16`

This problem can be reduced to find the longest subarray with sum of 1, or the longest subarray starting from left-most that has a sum greater than 0.

e.g. [6, 6, (6, 9, 9), 6, 6] => sum = 1

e.g. [9, 9, 9] => sum = 3

Time complexity: O(n)

Space complexity: O(n)

// Author: Huahua class Solution { public: int longestWPI(vector<int>& hours) { const int n = hours.size(); for (int& v : hours) v = v > 8 ? 1 : -1; int s = 0; unordered_map<int, int> idx; int ans = 0; for (int i = 0; i < hours.size(); ++i) { s += hours[i]; if (s > 0) ans = i + 1; if (!idx.count(s)) idx[s] = i; if (idx.count(s - 1)) ans = max(ans, i - idx[s - 1]); } return ans; } };

The post 花花酱 LeetCode 1124. Longest Well-Performing Interval appeared first on Huahua's Tech Road.

]]>The post 花花酱 LeetCode 1109. Corporate Flight Bookings appeared first on Huahua's Tech Road.

]]>`n`

flights, and they are labeled from `1`

to `n`

.
We have a list of flight bookings. The `i`

-th booking `bookings[i] = [i, j, k]`

means that we booked `k`

seats from flights labeled `i`

to `j`

inclusive.

Return an array `answer`

of length `n`

, representing the number of seats booked on each flight in order of their label.

**Example 1:**

Input:bookings = [[1,2,10],[2,3,20],[2,5,25]], n = 5Output:[10,55,45,25,25]

**Constraints:**

`1 <= bookings.length <= 20000`

`1 <= bookings[i][0] <= bookings[i][1] <= n <= 20000`

`1 <= bookings[i][2] <= 10000`

Time complexity: O(|bookings|)

Space complexity: O(n)

// Author: Huahua class Solution { public: vector<int> corpFlightBookings(vector<vector<int>>& bookings, int n) { vector<int> ans(n + 1); for (const auto& b : bookings) { ans[b[0] - 1] += b[2]; ans[b[1]] -= b[2]; } for (int i = 1; i < n; ++i) ans[i] += ans[i - 1]; ans.pop_back(); return ans; } };

The post 花花酱 LeetCode 1109. Corporate Flight Bookings appeared first on Huahua's Tech Road.

]]>The post 花花酱 LeetCode 1108. Defanging an IP Address appeared first on Huahua's Tech Road.

]]>`address`

, return a defanged version of that IP address.
A *defanged IP address* replaces every period `"."`

with `"[.]"`

.

**Example 1:**

Input:address = "1.1.1.1"Output:"1[.]1[.]1[.]1"

**Example 2:**

Input:address = "255.100.50.0"Output:"255[.]100[.]50[.]0"

**Constraints:**

- The given
`address`

is a valid IPv4 address.

Time complexity: O(n)

Space complexity: O(n)

class Solution { public: string defangIPaddr(string address) { string output; for (const char c : address) { if (c == '.') output += "[.]"; else output += c; } return output; } };

The post 花花酱 LeetCode 1108. Defanging an IP Address appeared first on Huahua's Tech Road.

]]>The post 花花酱 LeetCode 391. Perfect Rectangle appeared first on Huahua's Tech Road.

]]>Given N axis-aligned rectangles where N > 0, determine if they all together form an exact cover of a rectangular region.

Each rectangle is represented as a bottom-left point and a top-right point. For example, a unit square is represented as [1,1,2,2]. (coordinate of bottom-left point is (1, 1) and top-right point is (2, 2)).

**Example 1:**

rectangles = [ [1,1,3,3], [3,1,4,2], [3,2,4,4], [1,3,2,4], [2,3,3,4] ] Return true. All 5 rectangles together form an exact cover of a rectangular region.

**Example 2:**

rectangles = [ [1,1,2,3], [1,3,2,4], [3,1,4,2], [3,2,4,4] ] Return false. Because there is a gap between the two rectangular regions.

**Example 3:**

rectangles = [ [1,1,3,3], [3,1,4,2], [1,3,2,4], [3,2,4,4] ] Return false. Because there is a gap in the top center.

**Example 4:**

rectangles = [ [1,1,3,3], [3,1,4,2], [1,3,2,4], [2,2,4,4] ] Return false. Because two of the rectangles overlap with each other.

// Author: Huahua class Solution { public: bool isRectangleCover(vector<vector<int>>& rectangles) { set<pair<int, int>> corners; int area = 0; for (const auto& rect : rectangles) { pair<int, int> p1{rect[0], rect[1]}; pair<int, int> p2{rect[2], rect[1]}; pair<int, int> p3{rect[2], rect[3]}; pair<int, int> p4{rect[0], rect[3]}; for (const auto& p : {p1, p2, p3, p4}) { const auto& ret = corners.insert(p); if (!ret.second) corners.erase(ret.first); } area += (p3.first - p1.first) * (p3.second - p1.second); } if (corners.size() != 4) return false; const auto& p1 = *begin(corners); const auto& p3 = *rbegin(corners); return area == (p3.first - p1.first) * (p3.second - p1.second); } };

The post 花花酱 LeetCode 391. Perfect Rectangle appeared first on Huahua's Tech Road.

]]>The post 花花酱 LeetCode 1104. Path In Zigzag Labelled Binary Tree appeared first on Huahua's Tech Road.

]]>In the odd numbered rows (ie., the first, third, fifth,…), the labelling is left to right, while in the even numbered rows (second, fourth, sixth,…), the labelling is right to left.

Given the `label`

of a node in this tree, return the labels in the path from the root of the tree to the node with that `label`

.

**Example 1:**

Input:label = 14Output:[1,3,4,14]

**Example 2:**

Input:label = 26Output:[1,2,6,10,26]

**Constraints:**

`1 <= label <= 10^6`

Time complexity: O(logn)

Space complexity: O(logn)

// Author: Huahua class Solution { public: vector<int> pathInZigZagTree(int label) { deque<int> ans; while (label) { ans.push_front(label); int h = 31 - __builtin_clz(label); label = ((1 << h) + (1 << (h + 1)) - 1 - label) / 2; } return {begin(ans), end(ans)}; } };

The post 花花酱 LeetCode 1104. Path In Zigzag Labelled Binary Tree appeared first on Huahua's Tech Road.

]]>The post 花花酱 LeetCode 1106. Parsing A Boolean Expression appeared first on Huahua's Tech Road.

]]>Return the result of evaluating a given boolean `expression`

, represented as a string.

An expression can either be:

`"t"`

, evaluating to`True`

;`"f"`

, evaluating to`False`

;`"!(expr)"`

, evaluating to the logical NOT of the inner expression`expr`

;`"&(expr1,expr2,...)"`

, evaluating to the logical AND of 2 or more inner expressions`expr1, expr2, ...`

;`"|(expr1,expr2,...)"`

, evaluating to the logical OR of 2 or more inner expressions`expr1, expr2, ...`

**Example 1:**

Input:expression = "!(f)"Output:true

**Example 2:**

Input:expression = "|(f,t)"Output:true

**Example 3:**

Input:expression = "&(t,f)"Output:false

**Example 4:**

Input:expression = "|(&(t,f,t),!(t))"Output:false

Time complexity: O(n)

Space complexity: O(n)

// Author: Huahua class Solution { public: bool parseBoolExpr(string expression) { int s = 0; return parse(expression, s); } private: bool parse(const string& exp, int& s) { char ch = exp[s++]; if (ch == 't') return true; if (ch == 'f') return false; if (ch == '!') { bool ans = !parse(exp, ++s); ++s; return ans; } bool is_and = (ch == '&'); bool ans = is_and; ++s; while (true) { if (is_and) ans &= parse(exp, s); else ans |= parse(exp, s); if (exp[s++] == ')') break; } return ans; } };

The post 花花酱 LeetCode 1106. Parsing A Boolean Expression appeared first on Huahua's Tech Road.

]]>The post 花花酱 LeetCode 1105. Filling Bookcase Shelves appeared first on Huahua's Tech Road.

]]>We have a sequence of `books`

: the `i`

-th book has thickness `books[i][0]`

and height `books[i][1]`

.

We want to place these books **in order** onto bookcase shelves that have total width `shelf_width`

.

We choose some of the books to place on this shelf (such that the sum of their thickness is `<= shelf_width`

), then build another level of shelf of the bookcase so that the total height of the bookcase has increased by the maximum height of the books we just put down. We repeat this process until there are no more books to place.

Note again that at each step of the above process, the order of the books we place is the same order as the given sequence of books. For example, if we have an ordered list of 5 books, we might place the first and second book onto the first shelf, the third book on the second shelf, and the fourth and fifth book on the last shelf.

Return the minimum possible height that the total bookshelf can be after placing shelves in this manner.

**Example 1:**

Input:books = [[1,1],[2,3],[2,3],[1,1],[1,1],[1,1],[1,2]], shelf_width = 4Output:6Explanation:The sum of the heights of the 3 shelves are 1 + 3 + 2 = 6. Notice that book number 2 does not have to be on the first shelf.

**Constraints:**

`1 <= books.length <= 1000`

`1 <= books[i][0] <= shelf_width <= 1000`

`1 <= books[i][1] <= 1000`

dp[i] := min height of placing books[0] ~ books[i]

dp[-1] = 0

dp[j] = min{dp[i-1] + max(h[i] ~ h[j])}, 0 < i <= j, sum(w[i] ~ w[j]) <= shelf_width

Time complexity: O(n^2)

Space complexity: O(n)

// Author: Huahua, running time: 0 ms class Solution { public: int minHeightShelves(vector<vector<int>>& books, int sw) { int n = books.size(); vector<int> dp(n, INT_MAX / 2); for (int i = 0; i < n; ++i) { int w = 0; int h = 0; for (int j = i; j < n; ++j) { if ((w += books[j][0]) > sw) break; h = max(h, books[j][1]); dp[j] = min(dp[j], (i == 0 ? 0 : dp[i - 1]) + h); } } return dp.back(); } };

The post 花花酱 LeetCode 1105. Filling Bookcase Shelves appeared first on Huahua's Tech Road.

]]>The post 花花酱 LeetCode 1094. Car Pooling appeared first on Huahua's Tech Road.

]]>`capacity`

empty seats initially available for passengers. The vehicle Given a list of `trips`

, `trip[i] = [num_passengers, start_location, end_location]`

contains information about the `i`

-th trip: the number of passengers that must be picked up, and the locations to pick them up and drop them off. The locations are given as the number of kilometers due east from your vehicle’s initial location.

Return `true`

if and only if it is possible to pick up and drop off all passengers for all the given trips.

**Example 1:**

Input:trips = [[2,1,5],[3,3,7]], capacity = 4Output:false

**Example 2:**

Input:trips = [[2,1,5],[3,3,7]], capacity = 5Output:true

**Example 3:**

Input:trips = [[2,1,5],[3,5,7]], capacity = 3Output:true

**Example 4:**

Input:trips = [[3,2,7],[3,7,9],[8,3,9]], capacity = 11Output:true

Sort events by location

Time complexity: O(nlogn)

Space complexity: O(n)

// Author: Huahua class Solution { public: bool carPooling(vector<vector<int>>& trips, int capacity) { priority_queue<int> q; for (const auto& trip : trips) { int pick_up = -((trip[1] << 10) | (1 << 9) | trip[0]); int drop_off = -((trip[2] << 10) | trip[0]); q.push(pick_up); q.push(drop_off); } while (q.size()) { int key = -q.top(); q.pop(); int sign = ((key >> 9) & 1) ? 1: -1; int num = key & 0xFF; if ((capacity -= sign * num) < 0) return false; } return true; } };

Time complexity: O(n)

Space complexity: O(1000)

// Author: Huahua class Solution { public: bool carPooling(vector<vector<int>>& trips, int capacity) { vector<int> d(1001); for (const auto& trip : trips) { d[trip[1]] -= trip[0]; d[trip[2]] += trip[0]; } for (const int c : d) if ((capacity += c) < 0) return false; return true; } };

The post 花花酱 LeetCode 1094. Car Pooling appeared first on Huahua's Tech Road.

]]>The post 花花酱 LeetCode 23. Merge k Sorted Lists appeared first on Huahua's Tech Road.

]]>Merge *k* sorted linked lists and return it as one sorted list. Analyze and describe its complexity.

**Example:**

Input:[ 1->4->5, 1->3->4, 2->6 ]Output:1->1->2->3->4->4->5->6

Time complexity: O(nklogk)

Space complexity: O(k)

// Author: Huahua class Solution { public: ListNode* mergeKLists(vector<ListNode*>& lists) { ListNode dummy(0); ListNode *tail = &dummy; auto comp = [](ListNode* a, ListNode* b) { return a->val > b->val; }; priority_queue<ListNode*, vector<ListNode*>, decltype(comp)> q(comp); for (ListNode* list : lists) if (list) q.push(list); while (!q.empty()) { tail->next = q.top(); q.pop(); tail = tail->next; if (tail->next) q.push(tail->next); } return dummy.next; } };

Time complexity: O(nklogk)

Space complexity: O(logk)

// Author: Huahua class Solution { public: ListNode* mergeKLists(vector<ListNode*>& lists) { return merge(lists, 0, lists.size() - 1); } private: ListNode* merge(vector<ListNode*>& lists, int l, int r) { if (l > r) return nullptr; if (l == r) return lists[l]; if (l + 1 == r) return mergeTwoLists(lists[l], lists[r]); int m = l + (r - l) / 2; auto l1 = merge(lists, l, m); auto l2 = merge(lists, m + 1, r); return mergeTwoLists(l1, l2); } ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { ListNode dummy(0); ListNode* tail = &dummy; while (l1 && l2) { if (l1->val > l2->val) swap(l1, l2); tail->next = l1; l1 = l1->next; tail = tail->next; } if (l1) tail->next = l1; if (l2) tail->next = l2; return dummy.next; } };

The post 花花酱 LeetCode 23. Merge k Sorted Lists appeared first on Huahua's Tech Road.

]]>The post 花花酱 LeetCode 1092. Shortest Common Supersequence appeared first on Huahua's Tech Road.

]]>Given two strings `str1`

and `str2`

, return the shortest string that has both `str1`

and `str2`

as subsequences. If multiple answers exist, you may return any of them.

*(A string S is a subsequence of string T if deleting some number of characters from T (possibly 0, and the characters are chosen anywherefrom T) results in the string S.)*

**Example 1:**

Input:str1 = "abac", str2 = "cab"Output:"cabac"Explanation:str1 = "abac" is a substring of "cabac" because we can delete the first "c". str2 = "cab" is a substring of "cabac" because we can delete the last "ac". The answer provided is the shortest such string that satisfies these properties.

**Note:**

`1 <= str1.length, str2.length <= 1000`

`str1`

and`str2`

consist of lowercase English letters.

Find the LCS (longest common sub-sequence) of two strings, and insert unmatched characters into the LCS.

Time complexity: O(mn)

Space complexity: O(mn)

// Author: Huahua, running time: 16 ms, 15.3 MB class Solution { public: string shortestCommonSupersequence(string str1, string str2) { int l1 = str1.length(); int l2 = str2.length(); vector<vector<int>> dp(l1 + 1, vector<int>(l2 + 1)); for (int i = 1; i <= l1; ++i) for (int j = 1; j <= l2; ++j) dp[i][j] = str1[i - 1] == str2[j - 1] ? 1 + dp[i - 1][j - 1] : max(dp[i - 1][j], dp[i][j - 1]); deque<char> ans; while (l1 || l2) { char c; if (l1 == 0) c = str2[--l2]; else if (l2 == 0) c = str1[--l1]; else if (str1[l1 - 1] == str2[l2 - 1]) c = str1[--l1] = str2[--l2]; else if (dp[l1 - 1][l2] == dp[l1][l2]) c = str1[--l1]; else if (dp[l1][l2 - 1] == dp[l1][l2]) c = str2[--l2]; ans.push_front(c); } return {begin(ans), end(ans)}; } };

The post 花花酱 LeetCode 1092. Shortest Common Supersequence appeared first on Huahua's Tech Road.

]]>The post 花花酱 LeetCode 1073. Adding Two Negabinary Numbers appeared first on Huahua's Tech Road.

]]>`arr1`

and `arr2`

in base Each number is given in *array format*: as an array of 0s and 1s, from most significant bit to least significant bit. For example, `arr = [1,1,0,1]`

represents the number `(-2)^3 + (-2)^2 + (-2)^0 = -3`

. A number `arr`

in *array format* is also guaranteed to have no leading zeros: either `arr == [0]`

or `arr[0] == 1`

.

Return the result of adding `arr1`

and `arr2`

in the same format: as an array of 0s and 1s with no leading zeros.

**Example 1:**

Input:arr1 = [1,1,1,1,1], arr2 = [1,0,1]Output:[1,0,0,0,0]Explanation:arr1 represents 11, arr2 represents 5, the output represents 16.

**Note:**

`1 <= arr1.length <= 1000`

`1 <= arr2.length <= 1000`

`arr1`

and`arr2`

have no leading zeros`arr1[i]`

is`0`

or`1`

`arr2[i]`

is`0`

or`1`

Time complexity: O(n)

Space complexity: O(n)

// Author: Huahua, 8 ms, 9.2 MB class Solution { public: vector<int> addNegabinary(vector<int>& arr1, vector<int>& arr2) { int i = arr1.size(); int j = arr2.size(); int carry = 0; vector<int> ans; while (i || j || carry) { int sum = (i ? arr1[--i] : 0) + (j ? arr2[--j] : 0) + carry; ans.push_back(sum & 1); carry = -(sum >> 1); } while (ans.back() == 0 && ans.size() > 1) ans.pop_back(); reverse(begin(ans), end(ans)); return ans; } };

The post 花花酱 LeetCode 1073. Adding Two Negabinary Numbers appeared first on Huahua's Tech Road.

]]>The post 花花酱 1054. Distant Barcodes appeared first on Huahua's Tech Road.

]]>`i`

-th barcode is `barcodes[i]`

.
Rearrange the barcodes so that no two adjacent barcodes are equal. You may return any answer, and it is guaranteed an answer exists.

**Example 1:**

Input:[1,1,1,2,2,2]Output:[2,1,2,1,2,1]

**Example 2:**

Input:[1,1,1,1,2,2,3,3]Output:[1,3,1,3,2,1,2,1]

**Note:**

`1 <= barcodes.length <= 10000`

`1 <= barcodes[i] <= 10000`

Sort the element by their frequency in descending order. Fill the most frequent element first in even positions, if reach the end of the array, start from position 1 then 3, 5, …

Time complexity: O(nlogn)

Space complexity: O(n)

// Author: Huahua, 216 ms, 18.2 MB class Solution { public: vector<int> rearrangeBarcodes(vector<int>& barcodes) { const int n = barcodes.size(); vector<int> f(10001); for (int v : barcodes) ++f[v]; sort(begin(barcodes), end(barcodes), [&](const int a, const int b){ return f[a] == f[b] ? a > b : f[a] > f[b]; }); vector<int> ans(n); int pos = 0; for (int v : barcodes) { ans[pos] = v; if ((pos += 2) >= n) pos = 1; } return ans; } };

Actually, we only need to find the most frequent element and put in the even positions, then put the rest of the groups of elements in any order.

e.g. [1, 1, 2, 2, 2, 2, 2, 3, 4]

Can be

5*2 [2 – 2 – 2 – 2 – 2]

4*1 [2 4 2 – 2 – 2 – 2]

3*1 [2 4 2 3 2 – 2 – 2]

1*2 [ 2 3 2 3 2 1 2 1 2]

if we start with any other groups rather than 2, if will become:

[3 2 2 – 2 – 2 – 2 ] which is wrong…

Time complexity: O(n)

Space complexity: O(n)

// Author: Huahua, 172 ms (99.89%), 18 MB (< 100%) class Solution { public: vector<int> rearrangeBarcodes(vector<int>& barcodes) { constexpr int kMaxV = 10001; const int n = barcodes.size(); vector<int> f(kMaxV); int max_f = 0; int max_v = 0; for (int v : barcodes) if (++f[v] > max_f) { max_f = f[v]; max_v = v; } vector<int> ans(n); int pos = 0; while (f[max_v]-- > 0) { ans[pos] = max_v; if ((pos += 2)>= n) pos = 1; } for (int v = 1; v < kMaxV; ++v) { while (f[v]-- > 0) { ans[pos] = v; if ((pos += 2) >= n) pos = 1; } } return ans; } };

The post 花花酱 1054. Distant Barcodes appeared first on Huahua's Tech Road.

]]>The post 花花酱 LeetCode 1052. Grumpy Bookstore Owner appeared first on Huahua's Tech Road.

]]>`customers.length`

minutes. Every minute, some number of customers (`customers[i]`

) enter the store, and all those customers leave after the end of that minute.
On some minutes, the bookstore owner is grumpy. If the bookstore owner is grumpy on the i-th minute, `grumpy[i] = 1`

, otherwise `grumpy[i] = 0`

. When the bookstore owner is grumpy, the customers of that minute are not satisfied, otherwise they are satisfied.

The bookstore owner knows a secret technique to keep themselves not grumpy for `X`

minutes straight, but can only use it once.

Return the maximum number of customers that can be satisfied throughout the day.

**Example 1:**

Input:customers = [1,0,1,2,1,1,7,5], grumpy = [0,1,0,1,0,1,0,1], X = 3Output:16Explanation:The bookstore owner keeps themselves not grumpy for the last 3 minutes. The maximum number of customers that can be satisfied = 1 + 1 + 1 + 1 + 7 + 5 = 16.

**Note:**

`1 <= X <= customers.length == grumpy.length <= 20000`

`0 <= customers[i] <= 1000`

`0 <= grumpy[i] <= 1`

Sum the costumers of non grumpy minutes, recording the max sum of the sliding window of size X.

Time complexity: O(n)

Space complexity: o(n)

// Author: Huahua class Solution { public: int maxSatisfied(vector<int>& customers, vector<int>& grumpy, int X) { int base = 0; int window = 0; int best_window = 0; for (int i = 0; i < grumpy.size(); ++i) { (grumpy[i] ? window : base) += customers[i]; if (i >= X && grumpy[i - X]) window -= customers[i - X]; best_window = max(best_window, window); } return base + best_window; } };

The post 花花酱 LeetCode 1052. Grumpy Bookstore Owner appeared first on Huahua's Tech Road.

]]>The post 花花酱 LeetCode 1051. Height Checker appeared first on Huahua's Tech Road.

]]>Return the minimum number of students not standing in the right positions. (This is the number of students that must move in order for all students to be standing in non-decreasing order of height.)

**Example 1:**

Input:[1,1,4,2,1,3]Output:3Explanation:Students with heights 4, 3 and the last 1 are not standing in the right positions.

**Note:**

`1 <= heights.length <= 100`

`1 <= heights[i] <= 100`

Time complexity: O(nlogn)

Space complexity: O(n)

class Solution { public: int heightChecker(vector<int>& heights) { vector<int> h(heights); sort(begin(h), end(h)); int ans = 0; for (int i = 0; i < h.size(); ++i) ans += (heights[i] != h[i]); return ans; } };

The post 花花酱 LeetCode 1051. Height Checker appeared first on Huahua's Tech Road.

]]>