1524. 和为奇数的子数组数目
class Solution { public int numOfSubarrays(int[] arr) { int n = arr.length; int sum = 0; int res = 0, odd = 0, even = 1; for(int i = 1; i <= n; i++) { sum += if(arr[i-1] % 2 == 0) { res += odd; } else { res += even; } sum += arr[i-1]; if(sum % 2 == 0) even++; else odd++; } return res % 1000000007; } }
1525. 字符串的好分割数目
class Solution { public int numSplits(String s) { int n = s.length(); int count = 0; int[] left = new int[256], right = new int[256]; for(char c : s.toCharArray()) { if(right[c]++ == 0) count++; } int res = 0, l = 0, r = count; for(int i = 0; i < n - 1; i++) { char c = s.charAt(i); if(left[c]++ == 0) l++; if(--right[c] == 0) r--; if(l == r) res++; } return res; } }
5459. 形成目标数组的子数组最少增加次数
class Solution { public int minNumberOperations(int[] target) { int n = target.length; Stack<Integer> stack = new Stack<>(); stack.push(-1); int res = 0; for(int i = 0; i < n; i++) { while(!stack.empty() && stack.peek() > target[i]) { int top = stack.pop(); res += top - (Math.max(target[i],stack.peek())); } if(stack.peek() == target[i]) continue; stack.push(target[i]); } return res + stack.pop(); } }
class Solution { public: int minNumberOperations(vector<int>& target) { int n = target.size(); int ans = target[0]; for (int i = 1; i < n; ++i) { ans += max(target[i] - target[i - 1], 0); } return ans; } };