# A. Percentage of Letter in String (opens new window)
Count frequency of each character.
DETAILS
class Solution {
public:
int percentageLetter(string s, char letter) {
int n = s.size(), c = 0;
for (auto ch : s)
c += (ch == letter);
return floor((100 * c) / n);
}
};
# B. Maximum Bags With Full Capacity of Rocks (opens new window)
DETAILS
class Solution {
public:
int maximumBags(vector<int>& C, vector<int>& R, int N) {
vector<int> res;
int idx = 0, n = C.size();
for (int i = 0; i < n; ++i)
res.push_back(C[i] - R[i]);
sort(res.begin(), res.end());
while (idx < n && N >= res[idx]) {
N -= res[idx];
idx++;
}
return idx;
}
};
def maximumBags(self, C: List[int], R: List[int], N: int) -> int:
res = sorted(c - r for c, r in zip(C, R))
i, n = 0, len(res)
while i < n and N >= res[i]:
N -= res[i]
i += 1
return i
# C. Minimum Lines to Represent a Line Chart (opens new window)
Calculate the slope of each segment.
DETAILS
class Solution {
public:
int minimumLines(vector<vector<int>>& A) {
sort(A.begin(), A.end(), [](const auto &a, const auto &b) { return a[0] < b[0]; });
if (A.size() < 3) return A.size() - 1;
int ans = 1, n = A.size();
for (int i = 2; i < n; ++i) {
ans += ((long)(A[i][1] - A[i - 1][1]) * (long)(A[i - 1][0] - A[i - 2][0]) != (long)(A[i - 1][1] - A[i - 2][1]) * (long)(A[i][0] - A[i - 1][0]) ? 1 : 0);
}
return ans;
}
};
# D. Sum of Total Strength of Wizards (opens new window)
Prefix sum of the prefix sum.
DETAILS
class Solution:
def totalStrength(self, A: List[int]) -> int:
mod, n = 10 ** 9 + 7, len(A)
right, st = [n] * n, []
for i in range(n):
while st and A[st[-1]] > A[i]:
right[st.pop()] = i
st.append(i)
left, st = [-1] * n, []
for i in range(n - 1, -1, -1):
while st and A[st[-1]] >= A[i]:
left[st.pop()] = i
st.append(i)
res, acc = 0, list(accumulate(accumulate(A), initial = 0))
for i in range(n):
l, r = left[i], right[i]
lacc, racc = acc[i] - acc[max(l, 0)], acc[r] - acc[i]
ln, rn = i - l, r - i
res += A[i] * (racc * ln - lacc * rn)
return res % mod