<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Flame Chan</title>
    <description>The latest articles on DEV Community by Flame Chan (@flame_chan_llll).</description>
    <link>https://dev.to/flame_chan_llll</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F1578017%2F2f0e91f4-8a4e-43c3-94ef-ff41f7374486.jpg</url>
      <title>DEV Community: Flame Chan</title>
      <link>https://dev.to/flame_chan_llll</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/flame_chan_llll"/>
    <language>en</language>
    <item>
      <title>LeetCode Day37 Dynamic Programming part 11</title>
      <dc:creator>Flame Chan</dc:creator>
      <pubDate>Fri, 19 Jul 2024 05:24:34 +0000</pubDate>
      <link>https://dev.to/flame_chan_llll/leetcode-day37-dynamic-programming-2079</link>
      <guid>https://dev.to/flame_chan_llll/leetcode-day37-dynamic-programming-2079</guid>
      <description>&lt;h1&gt;
  
  
  1143. Longest Common Subsequence
&lt;/h1&gt;

&lt;p&gt;Given two strings text1 and text2, return the length of their longest common subsequence. If there is no common subsequence, return 0.&lt;/p&gt;

&lt;p&gt;A subsequence of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters.&lt;/p&gt;

&lt;p&gt;For example, "ace" is a subsequence of "abcde".&lt;br&gt;
A common subsequence of two strings is a subsequence that is common to both strings.&lt;/p&gt;

&lt;p&gt;Example 1:&lt;/p&gt;

&lt;p&gt;Input: text1 = "abcde", text2 = "ace" &lt;br&gt;
Output: 3&lt;br&gt;&lt;br&gt;
Explanation: The longest common subsequence is "ace" and its length is 3.&lt;br&gt;
Example 2:&lt;/p&gt;

&lt;p&gt;Input: text1 = "abc", text2 = "abc"&lt;br&gt;
Output: 3&lt;br&gt;
Explanation: The longest common subsequence is "abc" and its length is 3.&lt;br&gt;
Example 3:&lt;/p&gt;

&lt;p&gt;Input: text1 = "abc", text2 = "def"&lt;br&gt;
Output: 0&lt;br&gt;
Explanation: There is no such common subsequence, so the result is 0.&lt;/p&gt;

&lt;p&gt;Constraints:&lt;/p&gt;

&lt;p&gt;1 &amp;lt;= text1.length, text2.length &amp;lt;= 1000&lt;br&gt;
text1 and text2 consist of only lowercase English characters.&lt;br&gt;
&lt;a href="https://leetcode.com/problems/longest-common-subsequence/description/" rel="noopener noreferrer"&gt;Original Page&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F74j2ogpzkuihu8857ydv.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F74j2ogpzkuihu8857ydv.png" alt="Image description" width="800" height="604"&gt;&lt;/a&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    public int longestCommonSubsequence(String text1, String text2) {

        int[][] dp = new int[text1.length()+1][text2.length()+1];
        int res = 0;
        for(int i=1; i&amp;lt;=text1.length(); i++){

            for(int j=1; j&amp;lt;=text2.length(); j++){
                dp[i][j] = dp[i-1][j];
                if(text1.charAt(i-1) == text2.charAt(j-1)){
                    //i-1, j-1 means the previous text1 substring and the previous text2 substring
                    dp[i][j] = dp[i-1][j-1] + 1;
                }else{
                    dp[i][j] = Math.max(dp[i][j-1], dp[i-1][j]);
                }
            }
        }
        // Arrays.stream(dp).map(Arrays::toString).forEach(System.out::println);
        return dp[text1.length()][text2.length()];
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h1&gt;
  
  
  1035. Uncrossed Lines
&lt;/h1&gt;

&lt;p&gt;You are given two integer arrays nums1 and nums2. We write the integers of nums1 and nums2 (in the order they are given) on two separate horizontal lines.&lt;/p&gt;

&lt;p&gt;We may draw connecting lines: a straight line connecting two numbers nums1[i] and nums2[j] such that:&lt;/p&gt;

&lt;p&gt;nums1[i] == nums2[j], and&lt;br&gt;
the line we draw does not intersect any other connecting (non-horizontal) line.&lt;br&gt;
Note that a connecting line cannot intersect even at the endpoints (i.e., each number can only belong to one connecting line).&lt;/p&gt;

&lt;p&gt;Return the maximum number of connecting lines we can draw in this way.&lt;/p&gt;

&lt;p&gt;Example 1:&lt;br&gt;
&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F804nc2cmgtlkj1o98w8h.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F804nc2cmgtlkj1o98w8h.png" alt="Image description" width="800" height="572"&gt;&lt;/a&gt;&lt;br&gt;
Input: nums1 = [1,4,2], nums2 = [1,2,4]&lt;br&gt;
Output: 2&lt;br&gt;
Explanation: We can draw 2 uncrossed lines as in the diagram.&lt;br&gt;
We cannot draw 3 uncrossed lines, because the line from nums1[1] = 4 to nums2[2] = 4 will intersect the line from nums1[2]=2 to nums2[1]=2.&lt;/p&gt;

&lt;p&gt;Example 2:&lt;br&gt;
Input: nums1 = [2,5,1,2,5], nums2 = [10,5,2,1,5,2]&lt;br&gt;
Output: 3&lt;/p&gt;

&lt;p&gt;Example 3:&lt;br&gt;
Input: nums1 = [1,3,7,1,7,5], nums2 = [1,9,2,5,1]&lt;br&gt;
Output: 2&lt;/p&gt;

&lt;p&gt;Constraints:&lt;/p&gt;

&lt;p&gt;1 &amp;lt;= nums1.length, nums2.length &amp;lt;= 500&lt;br&gt;
1 &amp;lt;= nums1[i], nums2[j] &amp;lt;= 2000&lt;br&gt;
&lt;a href="https://leetcode.com/problems/uncrossed-lines/description/" rel="noopener noreferrer"&gt;Original Page&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;This question is similar to the previous question, if the line does not cross, the max subsequence of the two given arrays will work as well.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    public int maxUncrossedLines(int[] nums1, int[] nums2) {
        int[][] dp = new int[2][nums1.length+1];

        for(int i=1; i&amp;lt;=nums2.length; i++){
            for(int j=1; j&amp;lt;=nums1.length; j++){
                if(nums1[j-1] == nums2[i-1]){
                    dp[i%2][j] = dp[(i-1)%2][j-1] + 1;
                }else{
                    dp[i%2][j] = Math.max(dp[i%2][j-1], dp[(i-1)%2][j]);
                }
            }

        }
        return dp[nums2.length%2][nums1.length];
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h1&gt;
  
  
  53. Maximum Subarray
&lt;/h1&gt;

&lt;p&gt;Given an integer array nums, find the &lt;br&gt;
subarray&lt;br&gt;
 with the largest sum, and return its sum.&lt;/p&gt;

&lt;p&gt;Example 1:&lt;/p&gt;

&lt;p&gt;Input: nums = [-2,1,-3,4,-1,2,1,-5,4]&lt;br&gt;
Output: 6&lt;br&gt;
Explanation: The subarray [4,-1,2,1] has the largest sum 6.&lt;br&gt;
Example 2:&lt;/p&gt;

&lt;p&gt;Input: nums = [1]&lt;br&gt;
Output: 1&lt;br&gt;
Explanation: The subarray [1] has the largest sum 1.&lt;br&gt;
Example 3:&lt;/p&gt;

&lt;p&gt;Input: nums = [5,4,-1,7,8]&lt;br&gt;
Output: 23&lt;br&gt;
Explanation: The subarray [5,4,-1,7,8] has the largest sum 23.&lt;/p&gt;

&lt;p&gt;Constraints:&lt;/p&gt;

&lt;p&gt;1 &amp;lt;= nums.length &amp;lt;= 10^5&lt;br&gt;
-10^4 &amp;lt;= nums[i] &amp;lt;= 10^4&lt;br&gt;
 &lt;a href="https://leetcode.com/problems/maximum-subarray/description/" rel="noopener noreferrer"&gt;Original Page&lt;/a&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    public int maxSubArray(int[] nums) {
        if(nums.length == 0){
            return 0;
        }
        int[] dp = new int[nums.length];
        dp[0] = nums[0];
        int res = dp[0];

        for(int i=1; i&amp;lt;nums.length; i++){

            dp[i] = Math.max(nums[i], dp[i-1]+nums[i]);

            res = Math.max(res, dp[i]);
        }

        // System.out.println(Arrays.toString(dp));
        return res;

    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
      <category>leetcode</category>
      <category>java</category>
      <category>algorithms</category>
    </item>
    <item>
      <title>LeetCode Day 36 Dynamic Programming Part 10</title>
      <dc:creator>Flame Chan</dc:creator>
      <pubDate>Fri, 19 Jul 2024 03:18:27 +0000</pubDate>
      <link>https://dev.to/flame_chan_llll/leetcode-day-36-dynamic-programming-part-10-2ecb</link>
      <guid>https://dev.to/flame_chan_llll/leetcode-day-36-dynamic-programming-part-10-2ecb</guid>
      <description>&lt;h1&gt;
  
  
  300. Longest Increasing Subsequence
&lt;/h1&gt;

&lt;p&gt;Given an integer array nums, return the length of the longest strictly increasing &lt;br&gt;
subsequence&lt;br&gt;
.&lt;/p&gt;

&lt;p&gt;Example 1:&lt;/p&gt;

&lt;p&gt;Input: nums = [10,9,2,5,3,7,101,18]&lt;br&gt;
Output: 4&lt;br&gt;
Explanation: The longest increasing subsequence is [2,3,7,101], therefore the length is 4.&lt;br&gt;
Example 2:&lt;/p&gt;

&lt;p&gt;Input: nums = [0,1,0,3,2,3]&lt;br&gt;
Output: 4&lt;br&gt;
Example 3:&lt;/p&gt;

&lt;p&gt;Input: nums = [7,7,7,7,7,7,7]&lt;br&gt;
Output: 1&lt;/p&gt;

&lt;p&gt;Constraints:&lt;/p&gt;

&lt;p&gt;1 &amp;lt;= nums.length &amp;lt;= 2500&lt;br&gt;
-10^4 &amp;lt;= nums[i] &amp;lt;= 10^4&lt;/p&gt;

&lt;p&gt;Follow up: Can you come up with an algorithm that runs in O(n log(n)) time complexity?&lt;br&gt;
&lt;a href="https://leetcode.com/problems/longest-increasing-subsequence/description/" rel="noopener noreferrer"&gt;Original Page&lt;/a&gt;&lt;/p&gt;
&lt;h2&gt;
  
  
  Wrong Code
&lt;/h2&gt;


&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    public int lengthOfLIS(int[] nums) {
        int start = nums[0];
        int pre = nums[0];
        int preMax = nums[0];
        int cnt = 1;
        int max = 1;

        for(int i=1; i&amp;lt;nums.length; i++){
            if(nums[i] &amp;lt; start){
                max = Math.max(max, cnt);
                start = nums[i];
                cnt = 1;
            } 
            else if(nums[i] &amp;gt; pre){
                cnt ++;
            }
            pre = nums[i];
            System.out.println("cur:"+nums[i] + " pre:"+pre+ " count:" + cnt);
        }
        return Math.max(max, cnt);
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;h2&gt;
  
  
  Fix bug
&lt;/h2&gt;


&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;h2&gt;
  
  
  Learn From others treemap
&lt;/h2&gt;


&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    public int lengthOfLIS(int[] nums) {


        TreeMap&amp;lt;Integer,Integer&amp;gt; map = new TreeMap&amp;lt;&amp;gt;();

        map.put(Integer.MIN_VALUE,0);

       for(int i: nums)
       {
           map.put(i,map.get(map.lowerKey(i))+1);
           while(map.higherKey(i)!=null &amp;amp;&amp;amp; map.get(map.higherKey(i))&amp;lt;=map.get(i)) 
           {
            map.remove(map.higherKey(i));
           }
       }

       return map.get(map.lastKey());

    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h1&gt;
  
  
  674. Longest Continuous Increasing Subsequence
&lt;/h1&gt;

&lt;p&gt;Given an unsorted array of integers nums, return the length of the longest continuous increasing subsequence (i.e. subarray). The subsequence must be strictly increasing.&lt;/p&gt;

&lt;p&gt;A continuous increasing subsequence is defined by two indices l and r (l &amp;lt; r) such that it is [nums[l], nums[l + 1], ..., nums[r - 1], nums[r]] and for each l &amp;lt;= i &amp;lt; r, nums[i] &amp;lt; nums[i + 1].&lt;/p&gt;

&lt;p&gt;Example 1:&lt;/p&gt;

&lt;p&gt;Input: nums = [1,3,5,4,7]&lt;br&gt;
Output: 3&lt;br&gt;
Explanation: The longest continuous increasing subsequence is [1,3,5] with length 3.&lt;br&gt;
Even though [1,3,5,7] is an increasing subsequence, it is not continuous as elements 5 and 7 are separated by element&lt;br&gt;
4.&lt;br&gt;
Example 2:&lt;/p&gt;

&lt;p&gt;Input: nums = [2,2,2,2,2]&lt;br&gt;
Output: 1&lt;br&gt;
Explanation: The longest continuous increasing subsequence is [2] with length 1. Note that it must be strictly&lt;br&gt;
increasing.&lt;/p&gt;

&lt;p&gt;Constraints:&lt;/p&gt;

&lt;p&gt;1 &amp;lt;= nums.length &amp;lt;= 10^4&lt;br&gt;
-10^9 &amp;lt;= nums[i] &amp;lt;= 10^9&lt;br&gt;
&lt;a href="https://leetcode.com/problems/longest-continuous-increasing-subsequence/description/" rel="noopener noreferrer"&gt;Original Page&lt;/a&gt;&lt;/p&gt;
&lt;h2&gt;
  
  
  Greedy Algorithm
&lt;/h2&gt;


&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    public int findLengthOfLCIS(int[] nums) {
        if(nums.length &amp;lt; 1){
            return 0;
        }
        int res = 1;
        int cnt = 1;
        int pre = nums[0];
        for(int i=1; i&amp;lt;nums.length; i++){
            if(nums[i] &amp;gt; pre){
                cnt++;
            }else{
                res = Math.max(res, cnt);
                cnt = 1;
            }
            // System.out.println("cur: " + nums[i] + " pre:" + pre + " count:" + cnt);
            pre = nums[i];
        }
        return Math.max(res, cnt);
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;h2&gt;
  
  
  Dynamic Programming
&lt;/h2&gt;

&lt;p&gt;Different from the previous question, in this question we could only consider continuously increasing subsequences, which simplifies the process.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    public int findLengthOfLCIS(int[] nums) {
        if(nums.length &amp;lt; 1){
            return 0;
        }
        int res = 1;
        int[] dp = new int[nums.length];
        dp[0] = 1;

        for(int i=1; i&amp;lt;nums.length; i++){
            dp[i] = 1;
            if(nums[i] &amp;gt; nums[i-1]){
                dp[i] = dp[i-1] + 1;
                res = Math.max(res, dp[i]);
            }

        }
        // System.out.println(Arrays.toString(dp));
        return res;
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
      <category>leetcode</category>
      <category>java</category>
      <category>algorithms</category>
    </item>
    <item>
      <title>LeetCode Day 35 Dynamic Programming Part 9</title>
      <dc:creator>Flame Chan</dc:creator>
      <pubDate>Thu, 18 Jul 2024 02:19:36 +0000</pubDate>
      <link>https://dev.to/flame_chan_llll/leetcode-day-35-dynamic-programming-part-9-3fd5</link>
      <guid>https://dev.to/flame_chan_llll/leetcode-day-35-dynamic-programming-part-9-3fd5</guid>
      <description>&lt;h1&gt;
  
  
  188. Best Time to Buy and Sell Stock IV
&lt;/h1&gt;

&lt;p&gt;You are given an integer array prices where prices[i] is the price of a given stock on the ith day, and an integer k.&lt;/p&gt;

&lt;p&gt;Find the maximum profit you can achieve. You may complete at most k transactions: i.e. you may buy at most k times and sell at most k times.&lt;/p&gt;

&lt;p&gt;Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).&lt;/p&gt;

&lt;p&gt;Example 1:&lt;/p&gt;

&lt;p&gt;Input: k = 2, prices = [2,4,1]&lt;br&gt;
Output: 2&lt;br&gt;
Explanation: Buy on day 1 (price = 2) and sell on day 2 (price = 4), profit = 4-2 = 2.&lt;br&gt;
Example 2:&lt;/p&gt;

&lt;p&gt;Input: k = 2, prices = [3,2,6,5,0,3]&lt;br&gt;
Output: 7&lt;br&gt;
Explanation: Buy on day 2 (price = 2) and sell on day 3 (price = 6), profit = 6-2 = 4. Then buy on day 5 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3.&lt;/p&gt;

&lt;p&gt;Constraints:&lt;/p&gt;

&lt;p&gt;1 &amp;lt;= k &amp;lt;= 100&lt;br&gt;
1 &amp;lt;= prices.length &amp;lt;= 1000&lt;br&gt;
0 &amp;lt;= prices[i] &amp;lt;= 1000&lt;br&gt;
&lt;a href="https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/description/" rel="noopener noreferrer"&gt;Original Page&lt;/a&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    public int maxProfit(int k, int[] prices) {
        /**[0][0] do nothing in day 0
           [0][1] own the stock for 1st time in day 0
           [0][2] not own the stock for 1st time in day 0
           [0][3] own the stock for 2nd time in day 0
           [0][4] not own the stock for 2nd time in day 0
           ....
           [0][k*2-1] own the stock for kth time in day 0
           [0][k*2] not own the stock for kth time in day 0

           [1][1] = max([0][1],[0][0]-prices[1])
           [1][2] = max([0][2],[0][1]+prices[1])
           [1][3] = max([0][3],[0][2]-prices[1])

           [i][j] if j is odd means we need to pay for the stock or keep the own status
                  if j is even means we can sell the stock or keep the non-stock status

        */    
        int[][] dp = new int[prices.length+1][k*2+1];
        for(int i=1; i&amp;lt;=k*2; i+=2){
            dp[0][i] = -prices[0];
        }

        for(int i=1; i&amp;lt;prices.length; i++){
            for(int j=1; j&amp;lt;=k*2; j++){
                dp[i][j] = Math.max(
                    dp[i-1][j],
                    dp[i-1][j-1] + ((j % 2 == 0) ? 1 : -1) * prices[i]
                );
            }
        }
        return dp[prices.length-1][k*2];  
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h1&gt;
  
  
  309. Best Time to Buy and Sell Stock with Cooldown
&lt;/h1&gt;

&lt;p&gt;You are given an array prices where prices[i] is the price of a given stock on the ith day.&lt;/p&gt;

&lt;p&gt;Find the maximum profit you can achieve. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times) with the following restrictions:&lt;/p&gt;

&lt;p&gt;After you sell your stock, you cannot buy stock on the next day (i.e., cooldown one day).&lt;br&gt;
Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).&lt;/p&gt;

&lt;p&gt;Example 1:&lt;/p&gt;

&lt;p&gt;Input: prices = [1,2,3,0,2]&lt;br&gt;
Output: 3&lt;br&gt;
Explanation: transactions = [buy, sell, cooldown, buy, sell]&lt;br&gt;
Example 2:&lt;/p&gt;

&lt;p&gt;Input: prices = [1]&lt;br&gt;
Output: 0&lt;/p&gt;

&lt;p&gt;Constraints:&lt;/p&gt;

&lt;p&gt;1 &amp;lt;= prices.length &amp;lt;= 5000&lt;br&gt;
0 &amp;lt;= prices[i] &amp;lt;= 1000&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    public int maxProfit(int[] prices) {

        /**
        [0] own the stock
        [1] colldown 
        [2] not own the stock 

         */

         int[][] dp = new int[prices.length][3];

         dp[0][0] = -prices[0];

         for(int i=1; i&amp;lt;prices.length; i++){
            dp[i][0] = Math.max(dp[i-1][0], dp[i-1][2]-prices[i]);
            dp[i][1] = dp[i-1][0] + prices[i];
            dp[i][2] = Math.max(dp[i-1][1], dp[i-1][2]);
         }

        // Arrays.stream(dp).map(Arrays::toString).forEach(System.out::println);

         return Math.max(dp[prices.length-1][2],dp[prices.length-1][1]);

    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Be careful, that when it is cooldown, we cannot buy a new stock.&lt;/p&gt;

&lt;h2&gt;
  
  
  in this regression relation, it shows dp[2] is the last one we update so that we can keep covering cooldown condition. 
&lt;/h2&gt;

&lt;h1&gt;
  
  
  714. Best Time to Buy and Sell Stock with Transaction Fee
&lt;/h1&gt;

&lt;p&gt;You are given an array prices where prices[i] is the price of a given stock on the ith day, and an integer fee representing a transaction fee.&lt;/p&gt;

&lt;p&gt;Find the maximum profit you can achieve. You may complete as many transactions as you like, but you need to pay the transaction fee for each transaction.&lt;/p&gt;

&lt;p&gt;Note:&lt;/p&gt;

&lt;p&gt;You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).&lt;br&gt;
The transaction fee is only charged once for each stock purchase and sale.&lt;/p&gt;

&lt;p&gt;Example 1:&lt;/p&gt;

&lt;p&gt;Input: prices = [1,3,2,8,4,9], fee = 2&lt;br&gt;
Output: 8&lt;br&gt;
Explanation: The maximum profit can be achieved by:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Buying at prices[0] = 1&lt;/li&gt;
&lt;li&gt;Selling at prices[3] = 8&lt;/li&gt;
&lt;li&gt;Buying at prices[4] = 4&lt;/li&gt;
&lt;li&gt;Selling at prices[5] = 9
The total profit is ((8 - 1) - 2) + ((9 - 4) - 2) = 8.
Example 2:&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Input: prices = [1,3,7,5,10,3], fee = 3&lt;br&gt;
Output: 6&lt;/p&gt;

&lt;p&gt;Constraints:&lt;/p&gt;

&lt;p&gt;1 &amp;lt;= prices.length &amp;lt;= 5 * 10^4&lt;br&gt;
1 &amp;lt;= prices[i] &amp;lt; 5 * 10^4&lt;br&gt;
0 &amp;lt;= fee &amp;lt; 5 * 10^4&lt;br&gt;
&lt;a href="https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/description/" rel="noopener noreferrer"&gt;Original Page&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;the only thing we should consider is to add the transaction fee, but the fee will not change our previous logic&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    public int maxProfit(int[] prices, int fee) {
        int[] dp = new int[2];
        int temp = 0;

        dp[0] = -prices[0];

        for(int i=1; i&amp;lt;prices.length; i++){
            temp = dp[1];
            dp[1] = Math.max(dp[1], dp[0] + prices[i] -fee);
            dp[0] = Math.max(dp[0], temp-prices[i]);

        }

        return dp[1]; 
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
      <category>leetcode</category>
      <category>java</category>
      <category>algorithms</category>
    </item>
    <item>
      <title>LeetCode Day34 Dynamic Programming part8</title>
      <dc:creator>Flame Chan</dc:creator>
      <pubDate>Tue, 16 Jul 2024 04:37:48 +0000</pubDate>
      <link>https://dev.to/flame_chan_llll/leetcode-day34-dynamic-programming-part8-55hh</link>
      <guid>https://dev.to/flame_chan_llll/leetcode-day34-dynamic-programming-part8-55hh</guid>
      <description>&lt;h1&gt;
  
  
  121. Best Time to Buy and Sell Stock
&lt;/h1&gt;

&lt;p&gt;You are given an array prices where prices[i] is the price of a given stock on the ith day.&lt;/p&gt;

&lt;p&gt;You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock.&lt;/p&gt;

&lt;p&gt;Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0.&lt;/p&gt;

&lt;p&gt;Example 1:&lt;/p&gt;

&lt;p&gt;Input: prices = [7,1,5,3,6,4]&lt;br&gt;
Output: 5&lt;br&gt;
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.&lt;br&gt;
Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell.&lt;br&gt;
Example 2:&lt;/p&gt;

&lt;p&gt;Input: prices = [7,6,4,3,1]&lt;br&gt;
Output: 0&lt;br&gt;
Explanation: In this case, no transactions are done and the max profit = 0.&lt;/p&gt;

&lt;p&gt;Constraints:&lt;/p&gt;

&lt;p&gt;1 &amp;lt;= prices.length &amp;lt;= 10^5&lt;br&gt;
0 &amp;lt;= prices[i] &amp;lt;= 10^4&lt;br&gt;
&lt;a href="https://leetcode.com/problems/best-time-to-buy-and-sell-stock/description/" rel="noopener noreferrer"&gt;Original Page&lt;/a&gt;&lt;/p&gt;
&lt;h2&gt;
  
  
  Method 1, Greedy Algorithms
&lt;/h2&gt;


&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    public int maxProfit(int[] prices) {
        if(prices.length == 0){
            return 0;
        }

        int profit = 0;
        int buy = prices[0];
        for(int i=1; i&amp;lt;prices.length; i++ ){
            if(buy&amp;gt;=prices[i]){
                buy = prices[i];
            }else{
                profit = Math.max(profit, prices[i]-buy);
            }
        }
        return profit;
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;time O(n) space O(1)&lt;/p&gt;
&lt;h2&gt;
  
  
  Method 2 Dynamic Programming
&lt;/h2&gt;


&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    public int maxProfit(int[] prices) {
        if(prices.length == 0){
            return 0;
        }

        // 2 means we have 2 different status (have owned stock or not )
        int[][] dp = new int[prices.length][2];

        // if we want to own the stock we should pay for the specific price
        dp[0][0] = -prices[0];
        for(int i=1; i&amp;lt;dp.length; i++){
            dp[i][0] = Math.max(dp[i-1][0], -prices[i]);
            dp[i][1] = Math.max(dp[i-1][1], prices[i] + dp[i-1][0]);
        }
        // Arrays.stream(dp).map(Arrays::toString).forEach(System.out::println);
        return dp[dp.length-1][1];
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;time O(n) space O(n)&lt;br&gt;
Dynamic Programming is more general than greedy algorithms because it will not only work for the specific problem. &lt;/p&gt;
&lt;h1&gt;
  
  
  Method 2.1 (improve the space complexity)
&lt;/h1&gt;


&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    public int maxProfit(int[] prices) {
        if(prices.length == 0){
            return 0;
        }

        // 2 means we have 2 different status (have owned stock or not )
        int[] dp = new int[2];

        // if we want to own the stock we should pay for the specific price
        dp[0] = -prices[0];
        for(int i=1; i&amp;lt;prices.length; i++){
            dp[1] = Math.max(dp[1], prices[i] + dp[0]);
            dp[0] = Math.max(dp[0], -prices[i]);
        }
        // 
        return dp[1];
    }

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;Be careful here we should process dp[1] first because it will use the previous dp[0] instead of the updated dp[0].&lt;/p&gt;
&lt;h1&gt;
  
  
  122. Best Time to Buy and Sell Stock II
&lt;/h1&gt;

&lt;p&gt;You are given an integer array prices where prices[i] is the price of a given stock on the ith day.&lt;/p&gt;

&lt;p&gt;On each day, you may decide to buy and/or sell the stock. You can only hold at most one share of the stock at any time. However, you can buy it then immediately sell it on the same day.&lt;/p&gt;

&lt;p&gt;Find and return the maximum profit you can achieve.&lt;/p&gt;

&lt;p&gt;Example 1:&lt;/p&gt;

&lt;p&gt;Input: prices = [7,1,5,3,6,4]&lt;br&gt;
Output: 7&lt;br&gt;
Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4.&lt;br&gt;
Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3.&lt;br&gt;
Total profit is 4 + 3 = 7.&lt;br&gt;
Example 2:&lt;/p&gt;

&lt;p&gt;Input: prices = [1,2,3,4,5]&lt;br&gt;
Output: 4&lt;br&gt;
Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.&lt;br&gt;
Total profit is 4.&lt;br&gt;
Example 3:&lt;/p&gt;

&lt;p&gt;Input: prices = [7,6,4,3,1]&lt;br&gt;
Output: 0&lt;br&gt;
Explanation: There is no way to make a positive profit, so we never buy the stock to achieve the maximum profit of 0.&lt;/p&gt;

&lt;p&gt;Constraints:&lt;/p&gt;

&lt;p&gt;1 &amp;lt;= prices.length &amp;lt;= 3 * 10……4&lt;br&gt;
0 &amp;lt;= prices[i] &amp;lt;= 10……4&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    public int maxProfit(int[] prices) {
        if(prices.length &amp;lt;1){
            return 0;
        }

        int[][] dp = new int[prices.length][2];
        dp[0][0] = -prices[0];

        for(int i=1; i&amp;lt;prices.length; i++){
            //only when we do not own the stack we can buy a new stock
            dp[i][0] = Math.max(dp[i-1][1]-prices[i], dp[i-1][0]);
            dp[i][1] = Math.max(dp[i-1][0]+prices[i], dp[i-1][1]);
        }

        return dp[prices.length-1][1];
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The rolling array method&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    public int maxProfit(int[] prices) {
        if(prices.length &amp;lt;1){
            return 0;
        }

        int[] dp = new int[2];
        dp[0] = -prices[0];

        for(int i=1; i&amp;lt;prices.length; i++){
            //only when we do not own the stack we can buy a new stock
            dp[1] = Math.max(dp[0]+prices[i], dp[1]);
            dp[0] = Math.max(dp[1]-prices[i], dp[0]);

        }

        return dp[1];
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h1&gt;
  
  
  123. Best Time to Buy and Sell Stock III
&lt;/h1&gt;

&lt;p&gt;You are given an array prices where prices[i] is the price of a given stock on the ith day.&lt;/p&gt;

&lt;p&gt;Find the maximum profit you can achieve. You may complete at most two transactions.&lt;/p&gt;

&lt;p&gt;Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).&lt;/p&gt;

&lt;p&gt;Example 1:&lt;/p&gt;

&lt;p&gt;Input: prices = [3,3,5,0,0,3,1,4]&lt;br&gt;
Output: 6&lt;br&gt;
Explanation: Buy on day 4 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3.&lt;br&gt;
Then buy on day 7 (price = 1) and sell on day 8 (price = 4), profit = 4-1 = 3.&lt;br&gt;
Example 2:&lt;/p&gt;

&lt;p&gt;Input: prices = [1,2,3,4,5]&lt;br&gt;
Output: 4&lt;br&gt;
Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.&lt;br&gt;
Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are engaging multiple transactions at the same time. You must sell before buying again.&lt;br&gt;
Example 3:&lt;/p&gt;

&lt;p&gt;Input: prices = [7,6,4,3,1]&lt;br&gt;
Output: 0&lt;br&gt;
Explanation: In this case, no transaction is done, i.e. max profit = 0.&lt;/p&gt;

&lt;p&gt;Constraints:&lt;/p&gt;

&lt;p&gt;1 &amp;lt;= prices.length &amp;lt;= 10^5&lt;br&gt;
0 &amp;lt;= prices[i] &amp;lt;= 10^5&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    public int maxProfit(int[] prices) {
        int transactions = 2;
        int[][] dp = new int[prices.length][transactions*2+1];
        for(int i=1; i&amp;lt;=transactions; i++){
            dp[0][i*2-1] = -prices[0];
        }

        for(int i=1; i&amp;lt;prices.length; i++){

            dp[i][1] = Math.max(dp[i-1][0]-prices[i], dp[i-1][1]);
            dp[i][2] = Math.max(dp[i-1][1]+prices[i], dp[i-1][2]);
            dp[i][3] = Math.max(dp[i-1][2]-prices[i], dp[i-1][3]);
            dp[i][4] = Math.max(dp[i-1][3]+prices[i], dp[i-1][4]);
        }
        Arrays.stream(dp).map(Arrays::toString).forEach(System.out::println);

        return dp[prices.length-1][4];
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
      <category>leetcode</category>
      <category>java</category>
      <category>algorithms</category>
    </item>
    <item>
      <title>LeetCode Day33 Dynamic Programming</title>
      <dc:creator>Flame Chan</dc:creator>
      <pubDate>Mon, 15 Jul 2024 11:49:21 +0000</pubDate>
      <link>https://dev.to/flame_chan_llll/leetcode-day33-dynamic-programming-269l</link>
      <guid>https://dev.to/flame_chan_llll/leetcode-day33-dynamic-programming-269l</guid>
      <description>&lt;h1&gt;
  
  
  198. House Robber
&lt;/h1&gt;

&lt;p&gt;You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security systems connected and it will automatically contact the police if two adjacent houses were broken into on the same night.&lt;/p&gt;

&lt;p&gt;Given an integer array nums representing the amount of money of each house, return the maximum amount of money you can rob tonight without alerting the police.&lt;/p&gt;

&lt;p&gt;Example 1:&lt;/p&gt;

&lt;p&gt;Input: nums = [1,2,3,1]&lt;br&gt;
Output: 4&lt;br&gt;
Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3).&lt;br&gt;
Total amount you can rob = 1 + 3 = 4.&lt;br&gt;
Example 2:&lt;/p&gt;

&lt;p&gt;Input: nums = [2,7,9,3,1]&lt;br&gt;
Output: 12&lt;br&gt;
Explanation: Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1).&lt;br&gt;
Total amount you can rob = 2 + 9 + 1 = 12.&lt;/p&gt;

&lt;p&gt;Constraints:&lt;/p&gt;

&lt;p&gt;1 &amp;lt;= nums.length &amp;lt;= 100&lt;br&gt;
0 &amp;lt;= nums[i] &amp;lt;= 400&lt;br&gt;
&lt;a href="https://leetcode.com/problems/house-robber/description/" rel="noopener noreferrer"&gt;Original Page&lt;/a&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    public int rob(int[] nums) {
        int[] dp = new int[nums.length+1];
        dp[1] = nums[0];

        for(int i=2; i&amp;lt;dp.length; i++){
            dp[i] = Math.max(dp[i-2]+nums[i-1], dp[i-1]);
        }
        // System.out.println(Arrays.toString(dp));
        return dp[dp.length-1];

    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h1&gt;
  
  
  213. House Robber II
&lt;/h1&gt;

&lt;p&gt;You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed. All houses at this place are arranged in a circle. That means the first house is the neighbor of the last one. Meanwhile, adjacent houses have a security system connected, and it will automatically contact the police if two adjacent houses were broken into on the same night.&lt;/p&gt;

&lt;p&gt;Given an integer array nums representing the amount of money of each house, return the maximum amount of money you can rob tonight without alerting the police.&lt;/p&gt;

&lt;p&gt;Example 1:&lt;/p&gt;

&lt;p&gt;Input: nums = [2,3,2]&lt;br&gt;
Output: 3&lt;br&gt;
Explanation: You cannot rob house 1 (money = 2) and then rob house 3 (money = 2), because they are adjacent houses.&lt;br&gt;
Example 2:&lt;/p&gt;

&lt;p&gt;Input: nums = [1,2,3,1]&lt;br&gt;
Output: 4&lt;br&gt;
Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3).&lt;br&gt;
Total amount you can rob = 1 + 3 = 4.&lt;br&gt;
Example 3:&lt;/p&gt;

&lt;p&gt;Input: nums = [1,2,3]&lt;br&gt;
Output: 3&lt;/p&gt;

&lt;p&gt;Constraints:&lt;/p&gt;

&lt;p&gt;1 &amp;lt;= nums.length &amp;lt;= 100&lt;br&gt;
0 &amp;lt;= nums[i] &amp;lt;= 1000&lt;br&gt;
&lt;a href="https://leetcode.com/problems/house-robber-ii/description/" rel="noopener noreferrer"&gt;Original Page&lt;/a&gt;&lt;/p&gt;
&lt;h2&gt;
  
  
  Wrong Code
&lt;/h2&gt;


&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    public int rob(int[] nums) {
        int[] dp = new int[nums.length+1];

        boolean findFirst = false;

        dp[1] = nums[0];

        if(nums.length&amp;gt;2){
            if(nums[0]+nums[2] &amp;gt; nums[1]){
                dp[2] = Math.max(dp[1], nums[1]);
                dp[3] = nums[0] + nums[2];
                findFirst = true;
            }else{
                dp[2] = Math.max(dp[1], nums[1]);
                dp[3] = dp[2];
            }
        }

        for(int i=4; i&amp;lt;dp.length; i++){
            if(i == dp.length-1){
                if(findFirst){
                    dp[i] = dp[i-1];
                    break;
                }
            }
            dp[i] = Math.max(dp[i-1], dp[i-2]+nums[i-1]);
        }
        System.out.println(Arrays.toString(dp));
        return dp[dp.length-1];
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;in this case, we cannot cover the whole possibility.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    public int rob(int[] nums) {

        return Math.max(robber(nums, 0,nums.length-1), robber(nums,1,nums.length));


    }
    //dp[0] = 0 dp[1] = nums[1], dp[2] = max
    // begin 0, begin 1
        // [0,size-1] or [1, size]z
    public int robber(int[] nums, int beg, int end){
        int[] dp = new int[nums.length];
        if(beg == end){
            return nums[0];
        }
        dp[1] = nums[beg];

        for(int i=2; i&amp;lt;dp.length; i++){
            dp[i] = Math.max(dp[i-1], dp[i-2]+nums[beg + i - 1]);
        }
        // System.out.println(Arrays.toString(dp));
        return dp[dp.length-1];
    } 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
      <category>leetcode</category>
      <category>java</category>
      <category>algorithms</category>
    </item>
    <item>
      <title>LeetCode Day32 Dynamic Programming Part 5</title>
      <dc:creator>Flame Chan</dc:creator>
      <pubDate>Fri, 12 Jul 2024 04:56:13 +0000</pubDate>
      <link>https://dev.to/flame_chan_llll/leetcode-day32-dynamic-programming-part-5-1gna</link>
      <guid>https://dev.to/flame_chan_llll/leetcode-day32-dynamic-programming-part-5-1gna</guid>
      <description>&lt;h1&gt;
  
  
  518. Coin Change II
&lt;/h1&gt;

&lt;p&gt;You are given an integer array coins representing coins of different denominations and an integer amount representing a total amount of money.&lt;/p&gt;

&lt;p&gt;Return the number of combinations that make up that amount. If that amount of money cannot be made up by any combination of the coins, return 0.&lt;/p&gt;

&lt;p&gt;You may assume that you have an infinite number of each kind of coin.&lt;/p&gt;

&lt;p&gt;The answer is guaranteed to fit into a signed 32-bit integer.&lt;/p&gt;

&lt;p&gt;Example 1:&lt;/p&gt;

&lt;p&gt;Input: amount = 5, coins = [1,2,5]&lt;br&gt;
Output: 4&lt;br&gt;
Explanation: there are four ways to make up the amount:&lt;br&gt;
5=5&lt;br&gt;
5=2+2+1&lt;br&gt;
5=2+1+1+1&lt;br&gt;
5=1+1+1+1+1&lt;br&gt;
Example 2:&lt;/p&gt;

&lt;p&gt;Input: amount = 3, coins = [2]&lt;br&gt;
Output: 0&lt;br&gt;
Explanation: the amount of 3 cannot be made up just with coins of 2.&lt;br&gt;
Example 3:&lt;/p&gt;

&lt;p&gt;Input: amount = 10, coins = [10]&lt;br&gt;
Output: 1&lt;/p&gt;

&lt;p&gt;Constraints:&lt;/p&gt;

&lt;p&gt;1 &amp;lt;= coins.length &amp;lt;= 300&lt;br&gt;
1 &amp;lt;= coins[i] &amp;lt;= 5000&lt;br&gt;
All the values of coins are unique.&lt;br&gt;
0 &amp;lt;= amount &amp;lt;= 5000&lt;br&gt;
&lt;a href="https://leetcode.com/problems/coin-change-ii/description/" rel="noopener noreferrer"&gt;Original Page&lt;/a&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    public int change(int amount, int[] coins) {
        int[][] dp = new int[coins.length+1][amount+1];
        for(int i=0; i&amp;lt;=coins.length; i++){
            dp[i][0] = 1;
        }
        for(int i=1; i&amp;lt;= coins.length; i++){
            for(int j=1; j&amp;lt;=amount; j++){
                if(j&amp;lt;coins[i-1]){
                    dp[i][j] = dp[i-1][j];
                }else{
                    dp[i][j] = dp[i-1][j] + dp[i][j-coins[i-1]];
                }

            }
        }
                    // Arrays.stream(dp).map(Arrays::toString).forEach(System.out::println);
        return dp[coins.length][amount];
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    public int change(int amount, int[] coins) {
        int[] dp = new int[amount+1];
        dp[0] = 1;
        for(int i=0; i&amp;lt; coins.length; i++){
            for(int j=coins[i]; j&amp;lt;=amount; j++){
                dp[j] = dp[j] + dp[j-coins[i]];
            }
            System.out.println(Arrays.toString(dp));
        }
        return dp[amount];
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h1&gt;
  
  
  377. Combination Sum IV
&lt;/h1&gt;

&lt;p&gt;Given an array of distinct integers nums and a target integer target, return the number of possible combinations that add up to target.&lt;/p&gt;

&lt;p&gt;The test cases are generated so that the answer can fit in a 32-bit integer.&lt;/p&gt;

&lt;p&gt;Example 1:&lt;/p&gt;

&lt;p&gt;Input: nums = [1,2,3], target = 4&lt;br&gt;
Output: 7&lt;br&gt;
Explanation:&lt;br&gt;
The possible combination ways are:&lt;br&gt;
(1, 1, 1, 1)&lt;br&gt;
(1, 1, 2)&lt;br&gt;
(1, 2, 1)&lt;br&gt;
(1, 3)&lt;br&gt;
(2, 1, 1)&lt;br&gt;
(2, 2)&lt;br&gt;
(3, 1)&lt;br&gt;
Note that different sequences are counted as different combinations.&lt;br&gt;
Example 2:&lt;/p&gt;

&lt;p&gt;Input: nums = [9], target = 3&lt;br&gt;
Output: 0&lt;/p&gt;

&lt;p&gt;Constraints:&lt;/p&gt;

&lt;p&gt;1 &amp;lt;= nums.length &amp;lt;= 200&lt;br&gt;
1 &amp;lt;= nums[i] &amp;lt;= 1000&lt;br&gt;
All the elements of nums are unique.&lt;br&gt;
1 &amp;lt;= target &amp;lt;= 1000&lt;/p&gt;

&lt;p&gt;Follow up: What if negative numbers are allowed in the given array? How does it change the problem? What limitation we need to add to the question to allow negative numbers?&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    public int combinationSum4(int[] nums, int target) {
        int[] dp = new int[target+1];
        dp[0] = 1;
        for(int i=1; i&amp;lt;=target; i++){
            for(int j=0; j&amp;lt;nums.length; j++){
                if(nums[j] &amp;lt;= i){
                    dp[i] = dp[i] + dp[i-nums[j]];
                }
            }
            // System.out.println(Arrays.toString(dp));
        }
        return dp[target];
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
      <category>leetcode</category>
      <category>java</category>
      <category>algorithms</category>
    </item>
    <item>
      <title>LeetCode Day31 Dynamic Programming Part 4</title>
      <dc:creator>Flame Chan</dc:creator>
      <pubDate>Thu, 11 Jul 2024 10:22:51 +0000</pubDate>
      <link>https://dev.to/flame_chan_llll/leetcode-day31-dynamic-programming-part-4-4jn4</link>
      <guid>https://dev.to/flame_chan_llll/leetcode-day31-dynamic-programming-part-4-4jn4</guid>
      <description>&lt;h1&gt;
  
  
  494. Target Sum
&lt;/h1&gt;

&lt;p&gt;You are given an integer array nums and an integer target.&lt;/p&gt;

&lt;p&gt;You want to build an expression out of nums by adding one of the symbols '+' and '-' before each integer in nums and then concatenate all the integers.&lt;/p&gt;

&lt;p&gt;For example, if nums = [2, 1], you can add a '+' before 2 and a '-' before 1 and concatenate them to build the expression "+2-1".&lt;br&gt;
Return the number of different expressions that you can build, which evaluates to target.&lt;/p&gt;

&lt;p&gt;Example 1:&lt;/p&gt;

&lt;p&gt;Input: nums = [1,1,1,1,1], target = 3&lt;br&gt;
Output: 5&lt;br&gt;
Explanation: There are 5 ways to assign symbols to make the sum of nums be target 3.&lt;br&gt;
-1 + 1 + 1 + 1 + 1 = 3&lt;br&gt;
+1 - 1 + 1 + 1 + 1 = 3&lt;br&gt;
+1 + 1 - 1 + 1 + 1 = 3&lt;br&gt;
+1 + 1 + 1 - 1 + 1 = 3&lt;br&gt;
+1 + 1 + 1 + 1 - 1 = 3&lt;br&gt;
Example 2:&lt;/p&gt;

&lt;p&gt;Input: nums = [1], target = 1&lt;br&gt;
Output: 1&lt;/p&gt;

&lt;p&gt;Constraints:&lt;/p&gt;

&lt;p&gt;1 &amp;lt;= nums.length &amp;lt;= 20&lt;br&gt;
0 &amp;lt;= nums[i] &amp;lt;= 1000&lt;br&gt;
0 &amp;lt;= sum(nums[i]) &amp;lt;= 1000&lt;br&gt;
-1000 &amp;lt;= target &amp;lt;= 1000&lt;br&gt;
&lt;a href="https://leetcode.com/problems/target-sum/description/" rel="noopener noreferrer"&gt;Original Page&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Even though the backtracking is useful here we can use dynamic programming to solve this problem to achieve less time complexity.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    public int findTargetSumWays(int[] nums, int target) {
        /**
        sum(neg) + sum(pos) = sum(nums);
        sum(pos) - sum(neg) = target;
        sum(pos) = (sum(nums) + target) / 2 
         */
        int sum = Arrays.stream(nums).sum();
        // that means the sum of the positive number is invalid, because the nums do not conclude float
        if((sum+target)%2 != 0|| Math.abs(target) &amp;gt; sum){
            return 0;
        }

        // here we find the summary of the positive numbers
        int pos = (sum + target) &amp;gt;&amp;gt;1;

        // dp[i][j] array means for each index element `i` (nums[i]), if we want to reach the sum of the positive number `j`, we will have how many methods   
        int[][] dp = new int[nums.length+1][pos+1];

        // if we want to reach 0 we will have 1 ways that means we choose nothing and there is nothing.
        dp[0][0] = 1;

        // if(nums[0] &amp;lt;= pos){
        //     dp[0][nums[0]] = 1;
        // }

        for(int i = 1; i &amp;lt;= nums.length; i++){
            for(int j=0; j&amp;lt;=pos; j++){
                if(nums[i-1] &amp;gt; j){
                    dp[i][j] = dp[i-1][j];
                }else{
                    dp[i][j] = dp[i-1][j] + dp[i-1][j-nums[i-1]];
                }
            }
        }
        // Arrays.stream(dp).map(Arrays::toString).forEach(System.out::println);
        return dp[nums.length][pos];       

    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Note
&lt;/h2&gt;

&lt;h3&gt;
  
  
  1, init the dp array is important especially here it is important to find out that the meaning of 0
&lt;/h3&gt;

</description>
      <category>leetcode</category>
      <category>java</category>
      <category>algorithms</category>
    </item>
    <item>
      <title>LeetCode Day30 Dynamic Programming Part 3</title>
      <dc:creator>Flame Chan</dc:creator>
      <pubDate>Wed, 10 Jul 2024 05:28:05 +0000</pubDate>
      <link>https://dev.to/flame_chan_llll/leetcode-day30-dynamic-programming-part-3-4ma8</link>
      <guid>https://dev.to/flame_chan_llll/leetcode-day30-dynamic-programming-part-3-4ma8</guid>
      <description>&lt;h1&gt;
  
  
  0-1 Bag Problem
&lt;/h1&gt;

&lt;p&gt;Description of the topic&lt;/p&gt;

&lt;p&gt;Ming is a scientist who needs to attend an important international scientific conference to present his latest research. He needs to bring some research materials with him, but he has limited space in his suitcase. These research materials include experimental equipment, literature, experimental samples, etc., each of which occupies a different space and has a different value. &lt;/p&gt;

&lt;p&gt;Ming's luggage space is N. Ask Ming how he should choose to carry the research materials with the greatest value. Each research material can only be chosen once, and there are only two choices: choose or don't choose, and no cutting can be done.&lt;/p&gt;

&lt;p&gt;Input Description&lt;br&gt;
The first line contains two positive integers, the first integer M represents the type of research materials, and the second positive integer N represents Ming's luggage space.&lt;/p&gt;

&lt;p&gt;The second line contains M positive integers representing the space occupied by each type of research material. &lt;/p&gt;

&lt;p&gt;The third row contains M positive integers representing the value of each research material.&lt;/p&gt;

&lt;p&gt;Output Description&lt;br&gt;
Output an integer representing the maximum value of research materials that Ming can carry.&lt;/p&gt;

&lt;p&gt;Input Example&lt;br&gt;
6 1&lt;br&gt;
2 2 3 1 5 2&lt;br&gt;
2 3 1 5 4 3&lt;/p&gt;

&lt;p&gt;Output example&lt;br&gt;
5&lt;/p&gt;

&lt;p&gt;Hints&lt;br&gt;
Ming is able to carry 6 research materials, but the luggage space is only 1, and the research material that occupies 1 space is worth 5, so the final answer is output 5. &lt;/p&gt;

&lt;p&gt;Data range:&lt;br&gt;
1 &amp;lt;= N &amp;lt;= 5000&lt;br&gt;
1 &amp;lt;= M &amp;lt;= 5000&lt;br&gt;
The space occupied by the research materials and the value of the research materials are both less than or equal to 1000.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class Main{
    public static void main (String[] args) {
    /* code */
    Scanner s = new Scanner(System.in);

        int M = s.nextInt();
        int N = s.nextInt();
        // clear buffer symbol /n
        s.nextLine();

    String w = s.nextLine();
    String v = s.nextLine();

    int[] weight = Arrays.stream(w.split(" "))
                        .mapToInt(Integer::valueOf)
                        .toArray();
    int[] value = Arrays.stream(v.split(" "))
                        .mapToInt(Integer::valueOf)
                        .toArray();

    int[][] dp = new int[M][N+1];


    for(int i=weight[0]; i&amp;lt;=N; i++){
        dp[0][i] = value[0];
    }

    for(int i=1; i&amp;lt;M; i++){
        for(int j=1; j&amp;lt;=N; j++){
            if(weight[i] &amp;gt; j){
                dp[i][j] = dp[i-1][j];
            }else{
                dp[i][j] = Math.max(dp[i - 1][j], dp[i - 1][j - weight[i]] + value[i]);
            }

        }
    }

    System.out.println(dp[M-1][N]);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;1, the dp array means that we can obtain the maximum value for item &lt;code&gt;i&lt;/code&gt; and target bag size &lt;code&gt;j&lt;/code&gt;. The row indicates the item, and the column represents the size of the bag.&lt;/p&gt;

&lt;p&gt;2, for init, we init the 1st row and 1st col( but actually we init the col by default 0, that mean )&lt;/p&gt;

&lt;p&gt;3, the regression relation is that: for each item:&lt;br&gt;
    a, if the weight of the item is heavier than the bag's size, we cannot choose the item and the current size is the size of the collection of the previously chosen items. &lt;br&gt;
    b, if the weight of the item is ok, we have to compare the size of the collection of the previously chosen items minus the size of the current item (if we do not do it, the total size will be the size + the size of the current item, it will break the logic of our dp array).&lt;/p&gt;

&lt;p&gt;Here, is the order of the double loop, because we can use a 2-D array to record all results and search for the current row from the previous row.&lt;/p&gt;
&lt;h2&gt;
  
  
  Also, we can use a 1-D array to realize it.
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    for(int i=1; i&amp;lt;M; i++){
        for(int j=1; j&amp;lt;=N; j++){
            if(weight[i] &amp;gt; j){
                dp[i][j] = dp[i-1][j];
            }else{
                dp[i][j] = Math.max(dp[i - 1][j], dp[i - 1][j - weight[i]] + value[i]);
            }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  change to
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;        int[] dp = new int[target+1];
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;        for(int i=1; i&amp;lt;nums.length; i++){
            for(int j=target; j&amp;gt;=1; j--){
                if(nums[i] &amp;gt; j){
                    continue;
                }
                dp[j] = Math.max(dp[j], dp[j-nums[i]] + nums[i]);    
            }
        }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;h1&gt;
  
  
  416. Partition Equal Subset Sum
&lt;/h1&gt;

&lt;p&gt;Given an integer array nums, return true if you can partition the array into two subsets such that the sum of the elements in both subsets is equal or false otherwise.&lt;/p&gt;

&lt;p&gt;Example 1:&lt;/p&gt;

&lt;p&gt;Input: nums = [1,5,11,5]&lt;br&gt;
Output: true&lt;br&gt;
Explanation: The array can be partitioned as [1, 5, 5] and [11].&lt;br&gt;
Example 2:&lt;/p&gt;

&lt;p&gt;Input: nums = [1,2,3,5]&lt;br&gt;
Output: false&lt;br&gt;
Explanation: The array cannot be partitioned into equal sum subsets.&lt;/p&gt;

&lt;p&gt;Constraints:&lt;/p&gt;

&lt;p&gt;1 &amp;lt;= nums.length &amp;lt;= 200&lt;br&gt;
1 &amp;lt;= nums[i] &amp;lt;= 100&lt;br&gt;
&lt;a href="https://leetcode.com/problems/partition-equal-subset-sum/description/" rel="noopener noreferrer"&gt;Original Page&lt;/a&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    public boolean canPartition(int[] nums) {
        int sum = Arrays.stream(nums).sum();
        if(sum%2==1){
            return false;
        }
        int target = sum&amp;gt;&amp;gt;1;
        int[][] dp = new int[nums.length][target+1];

        for(int i=nums[0]; i&amp;lt;=target; i++){
            dp[0][i] = nums[0];
        }

        for(int i=1; i&amp;lt;nums.length; i++){
            for(int j=1; j&amp;lt;=target; j++){
                if(nums[i] &amp;gt; j){
                    dp[i][j] = dp[i-1][j];
                }else{
                    dp[i][j] = Math.max(dp[i-1][j], dp[i-1][j-nums[i]] + nums[i]);
                }     
            }
        }

        return dp[nums.length-1][target] == target;  
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
      <category>leetcode</category>
      <category>java</category>
      <category>algorithms</category>
    </item>
    <item>
      <title>LeetCode Day29 Dynamic Programming Part 2</title>
      <dc:creator>Flame Chan</dc:creator>
      <pubDate>Tue, 09 Jul 2024 11:32:29 +0000</pubDate>
      <link>https://dev.to/flame_chan_llll/leetcode-day29-dynamic-programming-part-2-4np6</link>
      <guid>https://dev.to/flame_chan_llll/leetcode-day29-dynamic-programming-part-2-4np6</guid>
      <description>&lt;h1&gt;
  
  
  62. Unique Paths
&lt;/h1&gt;

&lt;p&gt;There is a robot on an m x n grid. The robot is initially located at the top-left corner (i.e., grid[0][0]). The robot tries to move to the bottom-right corner (i.e., grid[m - 1][n - 1]). The robot can only move either down or right at any point in time.&lt;/p&gt;

&lt;p&gt;Given the two integers m and n, return the number of possible unique paths that the robot can take to reach the bottom-right corner.&lt;/p&gt;

&lt;p&gt;The test cases are generated so that the answer will be less than or equal to 2 * 109.&lt;/p&gt;

&lt;p&gt;Example 1:&lt;/p&gt;

&lt;p&gt;Input: m = 3, n = 7&lt;br&gt;
Output: 28&lt;br&gt;
Example 2:&lt;/p&gt;

&lt;p&gt;Input: m = 3, n = 2&lt;br&gt;
Output: 3&lt;br&gt;
Explanation: From the top-left corner, there are a total of 3 ways to reach the bottom-right corner:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Right -&amp;gt; Down -&amp;gt; Down&lt;/li&gt;
&lt;li&gt;Down -&amp;gt; Down -&amp;gt; Right&lt;/li&gt;
&lt;li&gt;Down -&amp;gt; Right -&amp;gt; Down&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Constraints:&lt;/p&gt;

&lt;p&gt;1 &amp;lt;= m, n &amp;lt;= 100&lt;br&gt;
&lt;a href="https://leetcode.com/problems/unique-paths/description/" rel="noopener noreferrer"&gt;Original Page&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fac10rn096ydcoifri6fq.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fac10rn096ydcoifri6fq.png" alt="Image description" width="800" height="478"&gt;&lt;/a&gt;&lt;br&gt;
We can use this handwritten array simulation to explore the pattern (by the way, forgive my terrible handwriting).&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    public int uniquePaths(int m, int n) {
        if(n&amp;lt;=1 || m&amp;lt;=1){
            return 1;
        }
        int dp[][] = new int[m+1][n+1];
        dp[0][1] = 1;
        for(int i=1; i&amp;lt;m+1; i++){
            for(int j=1; j&amp;lt;n+1; j++){
                dp[i][j] = dp[i-1][j] + dp[i][j-1];
            }
        }
        return dp[m][n];

    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;dp[0][1] = 1;&lt;/code&gt; for this code, actually it does not matter whether we use dp[1][0] = 1 or dp[0][1] = 1, because we want to match the index to m and n, we extend one more row and column when we init the array see: &lt;code&gt;int dp[][] = new int[m+1][n+1];&lt;/code&gt;&lt;/p&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    public int uniquePathsWithObstacles(int[][] obstacleGrid) {
        int row = obstacleGrid.length;
        int col = obstacleGrid[0].length;

        int[][] dp = new int[row][col];

        boolean isBlocked = false;
        for(int i=0; i&amp;lt;row; i++){
            if(obstacleGrid[i][0]==1){
                isBlocked = true;
            }
                dp[i][0] = isBlocked ? 0 : 1;
        }

        isBlocked = false;
        for(int i=0; i&amp;lt;col; i++){

            if(obstacleGrid[0][i]==1){
                isBlocked = true;
            }
                dp[0][i] = isBlocked ? 0 : 1;
        }

        for(int i=1; i&amp;lt;row; i++){
            for(int j=1; j&amp;lt;col; j++){
                if(obstacleGrid[i][j] == 1){
                    dp[i][j] = 0;
                }else{
                    dp[i][j] = dp[i-1][j] + dp[i][j-1];
                }
            }
        }
        // Arrays.stream(dp).map(Arrays::toString).forEach(System.out::println);
        return dp[row-1][col-1];  
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;There is nothing especially hard to realize, we only need to consider the blocked thing but it is easy to think, which implies that when there is a blocked one, the grid that is left or down to the blocked one can not be reached through this direction. (the A grid's left grid is a blocked one, we can not from A's left moving to A, we can only find the up route, and this logic work for up as well) &lt;/p&gt;

&lt;h1&gt;
  
  
  343. Integer Break
&lt;/h1&gt;

&lt;p&gt;Given an integer n, break it into the sum of k positive integers, where k &amp;gt;= 2, and maximize the product of those integers.&lt;/p&gt;

&lt;p&gt;Return the maximum product you can get.&lt;/p&gt;

&lt;p&gt;Example 1:&lt;/p&gt;

&lt;p&gt;Input: n = 2&lt;br&gt;
Output: 1&lt;br&gt;
Explanation: 2 = 1 + 1, 1 × 1 = 1.&lt;br&gt;
Example 2:&lt;/p&gt;

&lt;p&gt;Input: n = 10&lt;br&gt;
Output: 36&lt;br&gt;
Explanation: 10 = 3 + 3 + 4, 3 × 3 × 4 = 36.&lt;/p&gt;

&lt;p&gt;Constraints:&lt;/p&gt;

&lt;p&gt;2 &amp;lt;= n &amp;lt;= 58&lt;br&gt;
&lt;a href="https://leetcode.com/problems/integer-break/description/" rel="noopener noreferrer"&gt;Original Page&lt;/a&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    public int integerBreak(int n) {
        if(n&amp;lt;=2){
            return 1;
        }
        //init
        int[] dp = new int[n+1];
        dp[1] = 1;
        dp[2] = 1;
        //logic
        for(int i=3; i&amp;lt;=n; i++){
            for(int num=1; num&amp;lt;i; num++){
                dp[i] = Math.max(
                    Math.max(num * (i - num), dp[i]),
                    num * dp[i - num]);

            }
        }

        // Arrays.stream(dp).forEach(System.out::println);
        return dp[dp.length-1];
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
      <category>leetcode</category>
      <category>java</category>
      <category>algorithms</category>
    </item>
    <item>
      <title>LeetCode Day28 Dynamic Programming Part1</title>
      <dc:creator>Flame Chan</dc:creator>
      <pubDate>Mon, 08 Jul 2024 10:24:25 +0000</pubDate>
      <link>https://dev.to/flame_chan_llll/leetcode-day28-dynamic-programming-part1-17o0</link>
      <guid>https://dev.to/flame_chan_llll/leetcode-day28-dynamic-programming-part1-17o0</guid>
      <description>&lt;h1&gt;
  
  
  509. Fibonacci Number
&lt;/h1&gt;

&lt;p&gt;The Fibonacci numbers, commonly denoted F(n) form a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones, starting from 0 and 1. That is,&lt;/p&gt;

&lt;p&gt;F(0) = 0, F(1) = 1&lt;br&gt;
F(n) = F(n - 1) + F(n - 2), for n &amp;gt; 1.&lt;br&gt;
Given n, calculate F(n).&lt;/p&gt;

&lt;p&gt;Example 1:&lt;/p&gt;

&lt;p&gt;Input: n = 2&lt;br&gt;
Output: 1&lt;br&gt;
Explanation: F(2) = F(1) + F(0) = 1 + 0 = 1.&lt;br&gt;
Example 2:&lt;/p&gt;

&lt;p&gt;Input: n = 3&lt;br&gt;
Output: 2&lt;br&gt;
Explanation: F(3) = F(2) + F(1) = 1 + 1 = 2.&lt;br&gt;
Example 3:&lt;/p&gt;

&lt;p&gt;Input: n = 4&lt;br&gt;
Output: 3&lt;br&gt;
Explanation: F(4) = F(3) + F(2) = 2 + 1 = 3.&lt;/p&gt;

&lt;p&gt;Constraints:&lt;/p&gt;

&lt;p&gt;0 &amp;lt;= n &amp;lt;= 30&lt;br&gt;
&lt;a href="https://leetcode.com/problems/fibonacci-number/description/" rel="noopener noreferrer"&gt;Original Page&lt;/a&gt;&lt;/p&gt;
&lt;h2&gt;
  
  
  Recursion Method
&lt;/h2&gt;


&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    public int fib(int n) {
        if(n==0){
            return 0;
        }     
        else if(n==1){
            return 1;
        }   
        else{
            return fib(n-1) + fib(n-2);
        }
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;The Recursion Method is like DFS to go deep and then do the backtracking to get the final answer. &lt;br&gt;
time: O(2^n)&lt;br&gt;
space: O(1)&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    private int[] dp = new int[31];
    public int fib(int n) {
        if(n&amp;lt;2){
            dp[n] = n;
            return n;
        }  

        if(n&amp;gt;=2 &amp;amp;&amp;amp; dp[n]!=0){
            return dp[n];
        }

        dp[n] = fib(n-1) + fib(n-2);
        return dp[n];
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;we can use a global array to save the result to avoid re-recursion of the same elements. e.g. the figure below displays that f(17) and f(18) are two different recursion routes and if we use the normal recursion method we have to calculate them more than once. &lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F79sjjm3pek04x30yb1un.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F79sjjm3pek04x30yb1un.png" alt="Image description" width="800" height="415"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;time: O(n), space: O(n)&lt;/p&gt;

&lt;h2&gt;
  
  
  Dynamic Programming
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    public int fib(int n) {
        if(n&amp;lt;2){
            return n;
        }
        int[] dp = new int[n+1];
        dp[0] = 0;
        dp[1] = 1;
        for(int i=2; i&amp;lt;=n; i++){
            dp[i] = dp[i-1] + dp[i-2];
        }
        return dp[n];
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The recursion works from top to bottom and then backtracking, the memory recursion will save the recursion results to avoid double calculation. Now the dynamic programming works from the bottom to the top and saves each step's result to the dp array. &lt;br&gt;
time: O(n)&lt;br&gt;
space: O(n)&lt;/p&gt;
&lt;h2&gt;
  
  
  Also we can dynamically update the limit num instead of an array. This will save space complexity, especially for a huge number of elements.
&lt;/h2&gt;


&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    public int fib(int n) {
        if(n&amp;lt;2){
            return n;
        }
        int start = 0;
        int pre = 1;
        int res = pre;

        for(int i=2; i&amp;lt;=n; i++){
            res = start + pre;
            start = pre;
            pre = res;
        }
        return res;
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;h1&gt;
  
  
  70. Climbing Stairs
&lt;/h1&gt;

&lt;p&gt;You are climbing a staircase. It takes n steps to reach the top.&lt;/p&gt;

&lt;p&gt;Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?&lt;/p&gt;

&lt;p&gt;Example 1:&lt;/p&gt;

&lt;p&gt;Input: n = 2&lt;br&gt;
Output: 2&lt;br&gt;
Explanation: There are two ways to climb to the top.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;1 step + 1 step&lt;/li&gt;
&lt;li&gt;2 steps
Example 2:&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Input: n = 3&lt;br&gt;
Output: 3&lt;br&gt;
Explanation: There are three ways to climb to the top.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;1 step + 1 step + 1 step&lt;/li&gt;
&lt;li&gt;1 step + 2 steps&lt;/li&gt;
&lt;li&gt;2 steps + 1 step&lt;/li&gt;
&lt;/ol&gt;
&lt;h1&gt;
  
  
  70. Climbing Stairs
&lt;/h1&gt;

&lt;p&gt;You are climbing a staircase. It takes n steps to reach the top.&lt;/p&gt;

&lt;p&gt;Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?&lt;/p&gt;

&lt;p&gt;Example 1:&lt;/p&gt;

&lt;p&gt;Input: n = 2&lt;br&gt;
Output: 2&lt;br&gt;
Explanation: There are two ways to climb to the top.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;1 step + 1 step&lt;/li&gt;
&lt;li&gt;2 steps
Example 2:&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Input: n = 3&lt;br&gt;
Output: 3&lt;br&gt;
Explanation: There are three ways to climb to the top.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;1 step + 1 step + 1 step&lt;/li&gt;
&lt;li&gt;1 step + 2 steps&lt;/li&gt;
&lt;li&gt;2 steps + 1 step&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Constraints:&lt;/p&gt;

&lt;p&gt;1 &amp;lt;= n &amp;lt;= 45&lt;br&gt;
&lt;a href="https://leetcode.com/problems/climbing-stairs/description/" rel="noopener noreferrer"&gt;Original Page&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fcwwj15pzwwlutmijeb0p.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fcwwj15pzwwlutmijeb0p.png" alt="Image description" width="800" height="522"&gt;&lt;/a&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    public int climbStairs(int n) {
        if(n&amp;lt;3){
            return n;
        }
        int[] dp = new int[n+1];
        dp[0] = 0;
        dp[1] = 1;
        dp[2] = 2;
        for(int i=3; i&amp;lt;=n; i++){
            dp[i] = dp[i-1] + dp[i-2];
        } 
        return dp[n];       
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    public int climbStairs(int n) {
        if(n&amp;lt;3){
            return n;
        }

        int prepre = 1;
        int pre = 2;
        int res = 0;
        for(int i=3; i&amp;lt;=n; i++){
            res = prepre + pre;
            prepre = pre;
            pre = res;
        } 
        return res;       
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h1&gt;
  
  
  746. Min Cost Climbing Stairs
&lt;/h1&gt;

&lt;p&gt;You are given an integer array cost where cost[i] is the cost of ith step on a staircase. Once you pay the cost, you can either climb one or two steps.&lt;/p&gt;

&lt;p&gt;You can either start from the step with index 0, or the step with index 1.&lt;/p&gt;

&lt;p&gt;Return the minimum cost to reach the top of the floor.&lt;/p&gt;

&lt;p&gt;Example 1:&lt;/p&gt;

&lt;p&gt;Input: cost = [10,15,20]&lt;br&gt;
Output: 15&lt;br&gt;
Explanation: You will start at index 1.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Pay 15 and climb two steps to reach the top.
The total cost is 15.
Example 2:&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Input: cost = [1,100,1,1,1,100,1,1,100,1]&lt;br&gt;
Output: 6&lt;br&gt;
Explanation: You will start at index 0.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Pay 1 and climb two steps to reach index 2.&lt;/li&gt;
&lt;li&gt;Pay 1 and climb two steps to reach index 4.&lt;/li&gt;
&lt;li&gt;Pay 1 and climb two steps to reach index 6.&lt;/li&gt;
&lt;li&gt;Pay 1 and climb one step to reach index 7.&lt;/li&gt;
&lt;li&gt;Pay 1 and climb two steps to reach index 9.&lt;/li&gt;
&lt;li&gt;Pay 1 and climb one step to reach the top.
The total cost is 6.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Constraints:&lt;/p&gt;

&lt;p&gt;2 &amp;lt;= cost.length &amp;lt;= 1000&lt;br&gt;
0 &amp;lt;= cost[i] &amp;lt;= 999&lt;br&gt;
&lt;a href="https://leetcode.com/problems/min-cost-climbing-stairs/description/" rel="noopener noreferrer"&gt;Original Page&lt;/a&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    public int minCostClimbingStairs(int[] cost) {
        if(cost.length &amp;lt; 2){
            return 0;
        }

        int[] dp = new int[cost.length+1];
        dp[0] = 0;
        dp[1] = 0;

        for(int i=2; i&amp;lt;dp.length; i++){
            dp[i] = Math.min(dp[i-1]+cost[i-1], dp[i-2]+cost[i-2]);
        }
        return dp[dp.length-1];

    }
the key thing of this problem is the `init array` and `the meaning of the array` and the `Recurrence relation`
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Be Careful that we should the question has told us that we can start from index 0 and index 1, which implies if the number of stairs is less than 2, we will cost 0 because we can start at that point and the behaviour of start will cost 0, only the behaviour of move cost.
&lt;/h3&gt;

</description>
      <category>leetcode</category>
      <category>java</category>
      <category>algorithms</category>
    </item>
    <item>
      <title>LeetCode Day27 Greedy Algorithms Part 5</title>
      <dc:creator>Flame Chan</dc:creator>
      <pubDate>Sat, 06 Jul 2024 11:48:14 +0000</pubDate>
      <link>https://dev.to/flame_chan_llll/leetcode-day27-greedy-algorithms-part-5-4gof</link>
      <guid>https://dev.to/flame_chan_llll/leetcode-day27-greedy-algorithms-part-5-4gof</guid>
      <description>&lt;h1&gt;
  
  
  56. Merge Intervals
&lt;/h1&gt;

&lt;p&gt;Given an array of intervals where intervals[i] = [starti, endi], merge all overlapping intervals, and return an array of the non-overlapping intervals that cover all the intervals in the input.&lt;/p&gt;

&lt;p&gt;Example 1:&lt;/p&gt;

&lt;p&gt;Input: intervals = [[1,3],[2,6],[8,10],[15,18]]&lt;br&gt;
Output: [[1,6],[8,10],[15,18]]&lt;br&gt;
Explanation: Since intervals [1,3] and [2,6] overlap, merge them into [1,6].&lt;br&gt;
Example 2:&lt;/p&gt;

&lt;p&gt;Input: intervals = [[1,4],[4,5]]&lt;br&gt;
Output: [[1,5]]&lt;br&gt;
Explanation: Intervals [1,4] and [4,5] are considered overlapping.&lt;/p&gt;

&lt;p&gt;Constraints:&lt;/p&gt;

&lt;p&gt;1 &amp;lt;= intervals.length &amp;lt;= 10^4&lt;br&gt;
intervals[i].length == 2&lt;br&gt;
0 &amp;lt;= starti &amp;lt;= endi &amp;lt;= 10^4&lt;br&gt;
&lt;a href="https://leetcode.com/problems/merge-intervals/description/" rel="noopener noreferrer"&gt;Original Page&lt;/a&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    public int[][] merge(int[][] intervals) {
        if(intervals.length &amp;lt;= 1){
            return intervals;
        }
        Arrays.sort(intervals, (a,b)-&amp;gt;{
            return Integer.compare(a[0], b[0]);
        });

        List&amp;lt;int[]&amp;gt; list = new ArrayList();
        for(int i=1; i&amp;lt;intervals.length; i++){
            if(intervals[i-1][1] &amp;gt;= intervals[i][0]){
                intervals[i][0] = intervals[i-1][0];
                intervals[i][1] = Math.max(intervals[i-1][1], intervals[i][1]);

            } else{
                list.add(intervals[i-1]);
            }
        }
        list.add(intervals[intervals.length-1]);
        return list.toArray(new int[list.size()][]);
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h1&gt;
  
  
  738. Monotone Increasing Digits
&lt;/h1&gt;

&lt;p&gt;An integer has monotone increasing digits if and only if each pair of adjacent digits x and y satisfy x &amp;lt;= y.&lt;/p&gt;

&lt;p&gt;Given an integer n, return the largest number that is less than or equal to n with monotone increasing digits.&lt;/p&gt;

&lt;p&gt;Example 1:&lt;/p&gt;

&lt;p&gt;Input: n = 10&lt;br&gt;
Output: 9&lt;br&gt;
Example 2:&lt;/p&gt;

&lt;p&gt;Input: n = 1234&lt;br&gt;
Output: 1234&lt;br&gt;
Example 3:&lt;/p&gt;

&lt;p&gt;Input: n = 332&lt;br&gt;
Output: 299&lt;/p&gt;

&lt;p&gt;Constraints:&lt;/p&gt;

&lt;p&gt;0 &amp;lt;= n &amp;lt;= 10^9&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    public int monotoneIncreasingDigits(int n) {
        if(n&amp;lt;10){
            return n;
        }
        String str = Integer.toString(n);
        char[] arr = new char[str.length()];
        arr[0] = str.charAt(0);

        int pos = -1;
        for(int i=1; i&amp;lt;str.length(); i++){
            char num = str.charAt(i);
            if(num &amp;lt; arr[i-1]){
                int j;
                if(pos == -1){
                    j = 0;
                }else{
                    j = pos;
                }
                for(;j&amp;lt;arr.length; j++){
                    if(j==0||j==pos){
                        arr[j] = (char) (arr[j]-1);
                    }else{
                        arr[j] = '9';
                    }
                }
                break;
            }
            else if(num &amp;gt; arr[i-1]){
                pos = i;
            }
            arr[i] = str.charAt(i);
        }
        if(arr[0] &amp;lt;=0){
            // cost space by using String
            str = new String(arr, 1,arr.length);
        }else{
            str = new String(arr);
        }
        return Integer.valueOf(str);
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fhvj4s28xj7emea06du1o.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fhvj4s28xj7emea06du1o.png" alt="Image description" width="800" height="469"&gt;&lt;/a&gt;&lt;/p&gt;

</description>
      <category>leetcode</category>
      <category>java</category>
      <category>algorithms</category>
    </item>
    <item>
      <title>LeetCode Day26 Greedy Algorithms Part 4</title>
      <dc:creator>Flame Chan</dc:creator>
      <pubDate>Fri, 05 Jul 2024 13:15:40 +0000</pubDate>
      <link>https://dev.to/flame_chan_llll/leetcode-day26-greedy-algorithms-part-4-5eoi</link>
      <guid>https://dev.to/flame_chan_llll/leetcode-day26-greedy-algorithms-part-4-5eoi</guid>
      <description>&lt;h1&gt;
  
  
  452. Minimum Number of Arrows to Burst Balloons
&lt;/h1&gt;

&lt;p&gt;There are some spherical balloons taped onto a flat wall that represents the XY-plane. The balloons are represented as a 2D integer array points where points[i] = [xstart, xend] denotes a balloon whose horizontal diameter stretches between xstart and xend. You do not know the exact y-coordinates of the balloons.&lt;/p&gt;

&lt;p&gt;Arrows can be shot up directly vertically (in the positive y-direction) from different points along the x-axis. A balloon with xstart and xend is burst by an arrow shot at x if xstart &amp;lt;= x &amp;lt;= xend. There is no limit to the number of arrows that can be shot. A shot arrow keeps traveling up infinitely, bursting any balloons in its path.&lt;/p&gt;

&lt;p&gt;Given the array points, return the minimum number of arrows that must be shot to burst all balloons.&lt;/p&gt;

&lt;p&gt;Example 1:&lt;/p&gt;

&lt;p&gt;Input: points = [[10,16],[2,8],[1,6],[7,12]]&lt;br&gt;
Output: 2&lt;br&gt;
Explanation: The balloons can be burst by 2 arrows:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Shoot an arrow at x = 6, bursting the balloons [2,8] and [1,6].&lt;/li&gt;
&lt;li&gt;Shoot an arrow at x = 11, bursting the balloons [10,16] and [7,12].
Example 2:&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Input: points = [[1,2],[3,4],[5,6],[7,8]]&lt;br&gt;
Output: 4&lt;br&gt;
Explanation: One arrow needs to be shot for each balloon for a total of 4 arrows.&lt;br&gt;
Example 3:&lt;/p&gt;

&lt;p&gt;Input: points = [[1,2],[2,3],[3,4],[4,5]]&lt;br&gt;
Output: 2&lt;br&gt;
Explanation: The balloons can be burst by 2 arrows:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Shoot an arrow at x = 2, bursting the balloons [1,2] and [2,3].&lt;/li&gt;
&lt;li&gt;Shoot an arrow at x = 4, bursting the balloons [3,4] and [4,5].&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Constraints:&lt;/p&gt;

&lt;p&gt;1 &amp;lt;= points.length &amp;lt;= 105&lt;br&gt;
points[i].length == 2&lt;br&gt;
-2^31 &amp;lt;= xstart &amp;lt; xend &amp;lt;= 2^31 - 1&lt;br&gt;
&lt;a href="https://leetcode.com/problems/minimum-number-of-arrows-to-burst-balloons/description/"&gt;Original Page&lt;/a&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    public int findMinArrowShots(int[][] points) {
        if(points.length == 0){
            return 0;
        }

        Arrays.sort(points, (a,b) -&amp;gt;{
            if(a[0] == b[0]){
                return a[1] - b[1];
            }
            return a[0] - b[0];
        });

        int arrow = 1;
        int start = points[0][0];
        int end = points[0][1];

        for(int i=0; i&amp;lt;points.length; i++){

            if((points[i][0] &amp;gt;= start &amp;amp;&amp;amp; points[i][0]&amp;lt;= end) ||
            (end &amp;gt;=points[i][0] &amp;amp;&amp;amp; end &amp;lt;= points[i][1])){

//Narrow the arrow point down 

                if(points[i][0] &amp;gt; start &amp;amp;&amp;amp; points[i][0] &amp;lt;= end){
                    start = points[i][0];
                }
                if(points[i][1]&amp;gt;start &amp;amp;&amp;amp; points[i][1] &amp;lt; end){
                    end = points[i][1];
                }
                continue;
            }else{

// current arrow point is not satisfied with balloons 

                start = points[i][0];
                end = points[i][1];
                arrow ++;   
            }
        }
        return arrow; 
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h1&gt;
  
  
  435. Non-overlapping Intervals
&lt;/h1&gt;

&lt;p&gt;Given an array of intervals intervals where intervals[i] = [starti, endi], return the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping.&lt;/p&gt;

&lt;p&gt;Example 1:&lt;/p&gt;

&lt;p&gt;Input: intervals = [[1,2],[2,3],[3,4],[1,3]]&lt;br&gt;
Output: 1&lt;br&gt;
Explanation: [1,3] can be removed and the rest of the intervals are non-overlapping.&lt;br&gt;
Example 2:&lt;/p&gt;

&lt;p&gt;Input: intervals = [[1,2],[1,2],[1,2]]&lt;br&gt;
Output: 2&lt;br&gt;
Explanation: You need to remove two [1,2] to make the rest of the intervals non-overlapping.&lt;br&gt;
Example 3:&lt;/p&gt;

&lt;p&gt;Input: intervals = [[1,2],[2,3]]&lt;br&gt;
Output: 0&lt;br&gt;
Explanation: You don't need to remove any of the intervals since they're already non-overlapping.&lt;/p&gt;

&lt;p&gt;Constraints:&lt;/p&gt;

&lt;p&gt;1 &amp;lt;= intervals.length &amp;lt;= 10^5&lt;br&gt;
intervals[i].length == 2&lt;br&gt;
-5 * 10^4 &amp;lt;= starti &amp;lt; endi &amp;lt;= 5 * 10^4&lt;br&gt;
&lt;a href="https://leetcode.com/problems/non-overlapping-intervals/description/"&gt;Original Page&lt;/a&gt;&lt;/p&gt;
&lt;h2&gt;
  
  
  Wrong Code
&lt;/h2&gt;


&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    public int eraseOverlapIntervals(int[][] intervals) {
        if(intervals.length == 0){
            return 0;
        }

        Arrays.sort(intervals, (a,b) -&amp;gt;{
            if(a[0] == b[0]){
                return a[1] - b[1];
            }
            return a[0] - b[0];
        });

        Arrays.stream(intervals)
                .map(Arrays::toString)
                .forEach(System.out::println);

        int count = 0;

        // List&amp;lt;int[]&amp;gt; list = new LinkedList&amp;lt;&amp;gt;();
        int start = intervals[0][0];
        int end = intervals[0][1];

        for(int i=1; i&amp;lt;intervals.length; i++){
            //if the left edge is not included in the previous interval the right will definitely not be in it.
            if(intervals[i][0] &amp;gt;=start &amp;amp;&amp;amp; intervals[i][0] &amp;lt;end){
                count++;
                continue;
            }
            start = intervals[i][0];
            end = intervals[i][1];
            // list.add(intervals[i]);
        }
        return count;
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Fix it
&lt;/h2&gt;


&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    public int eraseOverlapIntervals(int[][] intervals) {
        if(intervals.length == 0){
            return 0;
        }

        Arrays.sort(intervals, (a,b) -&amp;gt;{
            return a[0] - b[0];
        });

        int count = 0;

        int start = intervals[0][0];
        int end = intervals[0][1];

        for(int i=1; i&amp;lt;intervals.length; i++){
            if(intervals[i][0] &amp;lt; intervals[i-1][1]){
                count++;
                // here we need to find the maximum overlap, the means whether the next element  overlap to above groups of overlaps 
                // if only find overlap from the previous interval, it may cause miss calculation over-add 1 count
                intervals[i][1] = Math.min(intervals[i][1], intervals[i-1][1]);  
            }
        }
        return count;
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;h1&gt;
  
  
  763. Partition Labels
&lt;/h1&gt;

&lt;p&gt;You are given a string s. We want to partition the string into as many parts as possible so that each letter appears in at most one part.&lt;/p&gt;

&lt;p&gt;Note that the partition is done so that after concatenating all the parts in order, the resultant string should be s.&lt;/p&gt;

&lt;p&gt;Return a list of integers representing the size of these parts.&lt;/p&gt;

&lt;p&gt;Example 1:&lt;/p&gt;

&lt;p&gt;Input: s = "ababcbacadefegdehijhklij"&lt;br&gt;
Output: [9,7,8]&lt;br&gt;
Explanation:&lt;br&gt;
The partition is "ababcbaca", "defegde", "hijhklij".&lt;br&gt;
This is a partition so that each letter appears in at most one part.&lt;br&gt;
A partition like "ababcbacadefegde", "hijhklij" is incorrect, because it splits s into less parts.&lt;br&gt;
Example 2:&lt;/p&gt;

&lt;p&gt;Input: s = "eccbbbbdec"&lt;br&gt;
Output: [10]&lt;/p&gt;

&lt;p&gt;Constraints:&lt;/p&gt;

&lt;p&gt;1 &amp;lt;= s.length &amp;lt;= 500&lt;br&gt;
s consists of lowercase English letters.&lt;br&gt;
&lt;a href="https://leetcode.com/problems/partition-labels/description/"&gt;Original Page&lt;/a&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    public List&amp;lt;Integer&amp;gt; partitionLabels(String s) {
        List&amp;lt;Integer&amp;gt; list = new ArrayList&amp;lt;&amp;gt;();
        Set&amp;lt;Character&amp;gt; set = new HashSet&amp;lt;&amp;gt;();

        if(s.length() == 0){
            return list;
        }

        int start = 0;
        int end = 0;
        for(int i=0; i&amp;lt;s.length(); i++){
            Character target = s.charAt(i);

            if(!set.contains(target)){
                set.add(target);
                int j = s.length()-1;
                for(;j&amp;gt;i;j--){
                    if(s.charAt(j) == target){
                        break;
                    }
                }
                end = Math.max(end, j);
            }
            if(i == end){
                list.add(end-start+1);
                start = i+1;
                set.clear();
            } 
        }
        return list;
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    public List&amp;lt;Integer&amp;gt; partitionLabels(String s) {
        List&amp;lt;Integer&amp;gt; list = new ArrayList&amp;lt;&amp;gt;();
        Set&amp;lt;Character&amp;gt; set = new HashSet&amp;lt;&amp;gt;();

        int[] pos = new int[27];

        for(int i=s.length()-1; i&amp;gt;0;i--){
            if(pos[s.charAt(i)-'a'] == 0){
                pos[s.charAt(i)-'a'] = i;
            }
        }

        if(s.length() == 0){
            return list;
        }

        int start = 0;
        int end = 0;
        for(int i=0; i&amp;lt;s.length(); i++){
            Character target = s.charAt(i);

            if(!set.contains(target)){
                set.add(target);

                end = Math.max(end, pos[target-'a']);
            }
            if(i == end){
                list.add(end-start+1);
                start = i+1;
                set.clear();
            } 
        }
        return list;
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    public List&amp;lt;Integer&amp;gt; partitionLabels(String s) {
        List&amp;lt;Integer&amp;gt; list = new ArrayList&amp;lt;&amp;gt;();

        int[] pos = new int[27];

        for(int i=s.length()-1; i&amp;gt;0;i--){
            if(pos[s.charAt(i)-'a'] == 0){
                pos[s.charAt(i)-'a'] = i;
            }
        }

        if(s.length() == 0){
            return list;
        }

        int start = 0;
        int end = 0;
        for(int i=0; i&amp;lt;s.length(); i++){
            Character target = s.charAt(i);

            end = Math.max(end, pos[target-'a']);

            if(i == end){
                list.add(end-start+1);
                start = i+1;
            } 
        }
        return list;
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Because it is not important for evaluating whether the element has been in the set, we only focus on whether the end is reached or not, and if the same elements happen, the end will not change and if the different elements merge, it seems like end may change but all of them will not impact the if evaluation so we can remove them. &lt;/p&gt;

</description>
      <category>leetcode</category>
      <category>java</category>
      <category>algorithms</category>
    </item>
  </channel>
</rss>
