In this contest, because of carelessness, I forgot to consider the corner case in the first problem: the permutation count of 0 is 1. In the second problem, I simply reversed upper and lower. I got two penalties. Otherwise I probably could have entered the top 100. The problems were relatively simple, all standard problems, and previous original problems could be adapted with small changes.
classSolution { public: intdietPlanPerformance(vector<int>& calories, int k, int lower, int upper){ if (k > calories.size()) return0; int sum = accumulate(calories.begin(), calories.begin() + k, 0); int ans = 0; if (sum > upper) ++ans; elseif (sum < lower) --ans; for (int i = k; i < calories.size(); ++i) { sum = sum + calories[i] - calories[i - k]; if (sum > upper) ++ans; elseif (sum < lower) --ans; } return ans; } };
5175. Can Make Palindrome from Substring
Be sensitive to palindrome strings. Observation: a palindrome allows only one letter to have an odd count. Each replacement allows two additional odd counts.
Time complexity: O(max(s.size(), queries.size()). Space complexity: O(max(s.size(), queries.size()).
classSolution { public: vector<bool> canMakePaliQueries(string s, vector<vector<int>>& queries){ vector<int> count(26, 0); vector<vector<int>> prefix(s.size() + 1); prefix[0] = count; for (int i = 1; i < s.size() + 1; ++i) { ++count[s[i - 1] - 'a']; prefix[i] = count; } vector<bool> ans(queries.size()); for (int j = 0; j < queries.size(); ++j) { constauto& query = queries[j]; constauto& l = prefix[query[0]]; constauto& r = prefix[query[1] + 1]; int odd = 0; for (int i = 0; i < 26; ++i) { // cout << r[i] << ", " << l[i] << endl; int sub = r[i] - l[i]; if (sub % 2 == 1) { ++odd; } } ans[j] = odd <= 1 + 2 * query[2]; } return ans; } };
1178. Number of Valid Words for Each Puzzle
A variant of Trie.
First, the brute-force solution at least comes to mind: match every puzzle with every word. The time complexity is O(words.length * puzzles.length), and it will definitely time out. The optimization direction is to aggregate the information of word, and Trie is a very good data structure for that.
Time complexity: O(2^puzzles[i].length * puzzles.length, words.length * words[i].length). Space complexity: O(puzzles.length + min(2 ^ 26, words.length)).