[out of order version ā— sword finger offer] daily algorithm problem punch in problem solution - dynamic programming (topic No. 42,46,47,48)

Keywords: Java Algorithm leetcode Dynamic Programming

Punch in day7

Question 1: Sword finger Offer 42. Maximum sum of continuous subarrays

Enter an integer array. One or more consecutive integers in the array form a sub array. Find the maximum value of the sum of all subarrays.
The required time complexity is O(n).

Example 1:

Input: num = [- 2,1, - 3,4, - 1,2,1, - 5,4]
Output: 6
Explanation: the maximum sum of continuous subarray [4, - 1,2,1] is 6.

Tips:

1 <= arr.length <= 105
-100 <= arr[i] <= 100

Source: LeetCode
Link: https://leetcode-cn.com/problems/lian-xu-zi-shu-zu-de-zui-da-he-lcof

Problem solving ideas:
Continuous subarray, if you want the sum to become larger, the new number must be positive. (if the array itself is composed of negative numbers, the negative number with the smallest absolute value is the sum of the largest continuous subarray)
Using dynamic programming, dp[i] is defined to represent the maximum sum of continuous subarrays ending in nums[i].

Why the element num [i] must be included in the definition of maximum sum dp[i]: ensure the correctness of the recurrence of dp[i] to dp[i+1]; If nums[i] is not included, the continuous sub array requirements of the topic will not be met during recursion.

java code:

class Solution {
    public int maxSubArray(int[] nums) {
        int pre = 0, maxAns = nums[0];//Initializes the largest contiguous subarray
        for (int x : nums) {//Traversal array
            pre = Math.max(pre + x, x);
            maxAns = Math.max(maxAns, pre);
        }
        return maxAns;
    }
}

Question 2: Sword finger Offer 47. The maximum value of gifts

There is a gift in each grid of an m*n chessboard, and each gift has a certain value (value greater than 0). You can start from the upper left corner of the chessboard to take the gifts in the grid, and move one grid to the right or down at a time until you reach the lower right corner of the chessboard. Given the value of a chessboard and the gifts on it, please calculate the maximum value of gifts you can get?

Example 1:

Input:
[
[1,3,1],
[1,5,1],
[4,2,1]
]
Output: 12
Explanation: path 1 → 3 → 5 → 2 → 1 can get the most valuable gifts

Tips:

0 < grid.length <= 200 0 < grid[0].length <= 200

Source: LeetCode
Link: https://leetcode-cn.com/problems/li-wu-de-zui-da-jie-zhi-lcof

Problem solving ideas:

Let f(i,j) be the maximum cumulative value of the gift from the upper left corner of the chessboard to cell (I, J). It is easy to get the following recursive relationship: f(i,j) is equal to the larger value of f(i,j-1) and f(i-1,j) plus the current cell gift value grid(i,j).
f(i,j)=max[f(i,jāˆ’1),f(iāˆ’1,j)]+grid(i,j)

Therefore, dynamic programming can be used.

java code:

class Solution {
    public int maxValue(int[][] grid) {
    //m. n is the row height and column width of the matrix respectively
        int m = grid.length, n = grid[0].length;
        //Transfer equation
        for(int i = 0; i < m; i++) {
            for(int j = 0; j < n; j++) {
                if(i == 0 && j == 0) continue;
                if(i == 0) {
                	grid[i][j] += grid[i][j - 1] ;
                }
                else if(j == 0) {
                	grid[i][j] += grid[i - 1][j];
                }
                else 
                	grid[i][j] += Math.max(grid[i][j - 1], grid[i - 1][j]);
            }
        }
        return grid[m - 1][n - 1];//Returns the lower right element of dp matrix
    }
}


Question 3: Sword finger Offer 46. Translate numbers into strings

Given a number, we translate it into a string according to the following rules: 0 into "a", 1 into "b",..., 11 into "l",..., 25 into "z". A number may have multiple translations. Please program a function to calculate how many different translation methods there are for a number.

Example 1:

Input: 12258
Output: 5
Explanation: 12258 has five different translations, namely "bccfi", "bwfi", "bczi", "mcfi" and "mzi"

Tips:

0 <= num < 231

Source: LeetCode
Link: https://leetcode-cn.com/problems/ba-shu-zi-fan-yi-cheng-zi-fu-chuan-lcof

Problem solving ideas:
To push down the formula. Let the number of the ith translation scheme be f(i), and the last one will be left with 1 digit or 2 digits
When one digit is left, the number of previous translations is f(i-1)
When there are two digits left, the previous translation quantity is f(i-2), but at this time, if the two digits are greater than 25, it can only be disassembled into one translation.
So, this is a piecewise function

java code:

class Solution {
    public int translateNum(int num) {
    //Convert num to string type
        String s = String.valueOf(num);
        int a = 1, b = 1;
        for(int i = 2; i <= s.length(); i++) {//String traversal
            String tmp = s.substring(i - 2, i);//String slicing
            //a. B record dp[i], dp[i-1] respectively
            int c = tmp.compareTo("10") >= 0 && tmp.compareTo("25") <= 0 ? a + b : a;
            b = a;
            a = c;
        }
        return a;
    }
}

Question 4: Sword finger Offer 48. The longest substring without repeated characters

Please find the longest substring that does not contain duplicate characters from the string and calculate the length of the longest substring.

Example 1:

Enter: "abcabcbb"
Output: 3
Explanation: because the longest substring without repeated characters is "abc", its length is 3.

Example 2:

Enter: "bbbbb"
Output: 1
Explanation: because the longest substring without repeated characters is "b", its length is 1.

Example 3:

Input: "pwwkew"
Output: 3
Explanation: because the longest substring without repeated characters is "wke", its length is 3. Please note that your answer must be the length of the substring, "pwke" is a substring, not a substring.

Tips:

s.length <= 40000

Source: LeetCode
Link: https://leetcode-cn.com/problems/zui-chang-bu-han-zhong-fu-zi-fu-de-zi-zi-fu-chuan-lcof

Problem solving ideas:
The string length is N, so the number of substrings is (1+N)N/2.
It is solved by dynamic programming and hash table.

java code:

class Solution {
    public int lengthOfLongestSubstring(String s) {
        Map<Character, Integer> dic = new HashMap<>();
        int res = 0, tmp = 0;//initialization
        for(int j = 0; j < s.length(); j++) {
            int i = dic.getOrDefault(s.charAt(j), -1); // Get index i
            dic.put(s.charAt(j), j); // Update hash table
            tmp = tmp < j - i ? tmp + 1 : j - i; // dp[j - 1] -> dp[j]
            res = Math.max(res, tmp); // max(dp[j - 1], dp[j])
        }
        return res;
    }
}


Posted by GravityFX on Fri, 17 Sep 2021 09:19:17 -0700