iT邦幫忙

2023 iThome 鐵人賽

DAY 16
0

1004. Max Consecutive Ones III

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;
    }
}

Pick or not pick solution(Java).

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;
    }
}

上一篇
09/15
下一篇
09/17
系列文
30天準備google面試30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言