class Solution {public: int percentageLetter(string s, char letter) { int cnt = 0, len = s.length(); for (auto &c : s) { if (c == letter) { cnt++; } } return 100 * cnt / len; }};
2. Maximum Bags With Full Capacity of Rocks
Greedy.
● ● ●c++
class Solution {public: int maximumBags(vector<int>& capacity, vector<int>& rocks, int additionalRocks) { int n = capacity.size(); for (int i = 0; i < n; i++) { capacity[i] -= rocks[i]; } sort(capacity.begin(), capacity.end()); int ans = 0; for (int i = 0; i < n; i++) { int d = min(capacity[i], additionalRocks); capacity[i] -= d; additionalRocks -= d; if (capacity[i] == 0) { ans++; } } return ans; }};
3. Minimum Lines to Represent a Line Chart
Sort.
● ● ●c++
class Solution {public: int minimumLines(vector<vector<int>>& stockPrices) { map<int, int> points; for (auto &stock : stockPrices) { points[stock[0]] = stock[1]; } vector<pair<int, int>> pixels; for (auto &pair : points) { pixels.push_back(make_pair(pair.first, pair.second)); } int prevDx = 0, prevDy = 0, ans = 0; for (int i = 1; i < pixels.size(); i++) { int dx = pixels[i].first - pixels[i - 1].first; int dy = pixels[i].second - pixels[i - 1].second; int d = gcd(dx, dy); dx /= d; dy /= d; if (dx != prevDx || dy != prevDy) { ans++; prevDx = dx; prevDy = dy; } } return ans; }};
4. Sum of Total Strength of Wizards
Given element strength[i], we can find two positions L and R, where
L is either 0 or the largest one where strength[L - 1] <= strength[i];
R is either n - 1 or the smallest one where strengt[R + 1] > strength[i];
And we know, for any subarray [P, Q] (L <= P <= i and i <= Q <= R), the first minimum element is strength[i].
Now given strength[i], L and R, the answer contributed by strength[i] should be A + B where