Q: https://leetcode.com/problems/max-consecutive-ones-iii/description/
class Solution {
public int longestOnes(int[] nums, int k) {
int left = 0, right;
for (right = 0; right < nums.length; right++) {
if (nums[right] == 0) {
k--;
}
if (k < 0) {
// If the left element to be thrown out is zero we increase k.
k += 1 - nums[left];
left++;
}
}
return right - left;
}
}
Q: https://leetcode.com/problems/count-number-of-special-subsequences/description/
class Solution {
public int countSpecialSubsequences(int[] nums) {
Integer memo[][] = new Integer[nums.length][4];
int result = helper(0, 0, nums, memo);
return result;
}
private int helper(int index, int val, int[] nums, Integer memo[][]) {
int mod = 1000000007;
if (index == nums.length) {
if (val == 3) {
return 1;
}
return 0;
}
if (memo[index][val] != null) {
return memo[index][val];
}
int sum = 0;
if (nums[index] == val || nums[index] == val - 1) {
sum = (sum + helper(index + 1, nums[index] + 1, nums, memo)) % mod;
}
sum = (sum + helper(index + 1, val, nums, memo)) % mod;
memo[index][val] = sum;
return sum;
}
}