aboutsummaryrefslogtreecommitdiff
path: root/other/substr_largest_variance.cpp
diff options
context:
space:
mode:
authorJack Sangdahl <[email protected]>2025-03-10 00:36:13 -0600
committerJack Sangdahl <[email protected]>2025-03-10 00:36:13 -0600
commit7c60dee83b436e8e8a667bf9f191beced8de4fc3 (patch)
treeeb7a24ee2067f92245c57bb118e85a1baf15df50 /other/substr_largest_variance.cpp
parent5d7cdc215e4ba1ec4cbb24c084cccb5e5e641468 (diff)
downloadleetcode-7c60dee83b436e8e8a667bf9f191beced8de4fc3.tar.gz
leetcode-7c60dee83b436e8e8a667bf9f191beced8de4fc3.zip
chore: move cpp and rust code to directory
Diffstat (limited to 'other/substr_largest_variance.cpp')
-rw-r--r--other/substr_largest_variance.cpp48
1 files changed, 48 insertions, 0 deletions
diff --git a/other/substr_largest_variance.cpp b/other/substr_largest_variance.cpp
new file mode 100644
index 0000000..6df445c
--- /dev/null
+++ b/other/substr_largest_variance.cpp
@@ -0,0 +1,48 @@
+// 2272. Substring With Largest Variance
+#include "leetcode.h"
+
+/*
+ * the variance of a string is defined as the largest difference between the
+ * number of ocurrences of any '2' characters present in the string. note the
+ * two characters may or may not be the same. given a string 's', consisting of
+ * lowercase english letters only, return the largest variance possible among
+ * all substrings 's'. a substring is a contiguous sequence of characters witin
+ * a string.
+ */
+
+class Solution {
+public:
+ int largestVariance(string s) {
+ vector<int> arr(26);
+ for (auto i : s)
+ arr[i - 'a']++;
+ int ans = 0;
+ for (char i = 'a'; i <= 'z'; i++) {
+ for (char j = 'a'; j <= 'z'; j++) {
+ if (j == i || !arr[i - 'a'] || !arr[j - 'a'])
+ continue;
+ for (int k = 1; k <= 2; k++) {
+ int a1 = 0, a2 = 0;
+ for (auto l : s) {
+ if (l == i)
+ a1++;
+ if (l == j)
+ a2++;
+ if (a2 > a1)
+ a1 = 0, a2 = 0;
+ if (a1 && a2)
+ ans = max(ans, a1 - a2);
+ }
+ reverse(s.begin(), s.end());
+ }
+ }
+ }
+ return ans;
+ }
+};
+
+int main() {
+ Solution obj;
+ printf("%d\n", obj.largestVariance("aababbb")); // expect: 3
+ printf("%d\n", obj.largestVariance("abcde")); // expect: 0
+};