当前位置:网站首页>[interview high frequency questions] sequential DP questions with difficulty of 3/5 and direct construction
[interview high frequency questions] sequential DP questions with difficulty of 3/5 and direct construction
2022-06-24 15:53:00 【Gong Shui Sanye's Diary】
Title Description
This is a LeetCode Upper 「1537. Maximum score 」 , The difficulty is 「 difficult 」.
Tag : 「 The prefix and 」、「 structure 」、「 Double pointer 」、「 Sequence DP」、「 Dynamic programming 」
You have two Orderly And the elements in the array are different from each other nums1 and nums2 .
One Legal path The definition is as follows :
Select array nums1perhapsnums2To traverse the ( From the subscript Start at ).Traverses the current array from left to right . If you meet nums1andnums2Values that exist in , Then you can switch the path to another array corresponding to the number and continue to traverse ( But in a legal path, duplicate numbers are counted only once ).
Scores and numbers are defined as different paths .
Please return the maximum score of all possible legal paths .
Because the answer can be big , Please put it on Take the rest and return .
Example 1: 
Input :nums1 = [2,4,5,8,10], nums2 = [4,6,8,9]
Output :30
explain : The legal path includes :
[2,4,5,8,10], [2,4,5,8,9], [2,4,6,8,9], [2,4,6,8,10],( from nums1 To traverse the )
[4,6,8,9], [4,5,8,10], [4,5,8,9], [4,6,8,10] ( from nums2 To traverse the )
The maximum score is the green path in the figure above [2,4,6,8,10] .
Example 2:
Input :nums1 = [1,3,5,7,9], nums2 = [3,5,100]
Output :109
explain : The maximum score is from the path [1,3,5,100] obtain .
Example 3:
Input :nums1 = [1,2,3,4,5], nums2 = [6,7,8,9,10]
Output :40
explain :nums1 and nums2 There is no same number between .
The maximum score is from the path [6,7,8,9,10] obtain .
Example 4:
Input :nums1 = [1,4,5,8,9,11,19], nums2 = [2,3,4,11,12]
Output :61
Tips :
nums1andnums2Are strictly incremented arrays .
The prefix and + structure ( Piecewise calculation )
A simple and correct approach , We construct a decision scheme , So that the maximum score can be calculated directly .
First , In the best path, all common points must pass through , So we can merge points with equal values , That is to say, it is regarded as the same point .
Use both arrays to satisfy 「 Monotone increasing 」, We can go through The common points are calculated according to the complexity of , In binary Stored in the form of list Array ( The meaning of two tuples is ).
about list Each pair of adjacent elements in ( Adjacent common point ), Assuming that and , We can go through 「 The prefix and 」 To calculate the as well as And , Thus the decision is made in ( Or rather, , These two are the same point ) when , Which section should we go .
When the scores between all common points are calculated , For the first two ends of the best route , It's also a combination 「 The prefix and 」 Do the same logic processing .
Code :
class Solution {
int MOD = (int)1e9 + 7;
public int maxSum(int[] nums1, int[] nums2) {
int n = nums1.length, m = nums2.length;
long[] s1 = new long[n + 10], s2 = new long[m + 10];
for (int i = 1; i <= n; i++) s1[i] = s1[i - 1] + nums1[i - 1];
for (int i = 1; i <= m; i++) s2[i] = s2[i - 1] + nums2[i - 1];
List<int[]> list = new ArrayList<>();
for (int i = 0, j = 0; i < n && j < m; ) {
if (nums1[i] == nums2[j]) list.add(new int[]{i, j});
if (nums1[i] < nums2[j]) i++;
else j++;
}
long ans = 0;
for (int i = 0, p1 = -1, p2 = -1; i <= list.size(); i++) {
int idx1 = 0, idx2 = 0;
if (i < list.size()) {
int[] info = list.get(i);
idx1 = info[0]; idx2 = info[1];
} else {
idx1 = n - 1; idx2 = m - 1;
}
long t1 = s1[idx1 + 1] - s1[p1 + 1], t2 = s2[idx2 + 1] - s2[p2 + 1];
ans += Math.max(t1, t2);
p1 = idx1; p2 = idx2;
}
return (int)(ans % MOD);
}
}
Time complexity : Spatial complexity :
Sequence DP
Another common practice is 「 Sequence DP」 practice .
Definition On behalf of the nums1 Move on , arrive My biggest score ; Definition On behalf of the nums2 Move on , arrive My biggest score .
Because the analysis of the two is similar , We use For example .
Without losing general considerations How to transfer , Suppose the current processing is , according to Whether it is a public point , Discuss the situation by situation :
Not for public use , At this time, only Transfer from , That is to say ; For the public point ( Hypothesis and public ), At this point, you can start from or Transfer from , We need to take and The maximum of , That is to say .
what's more , We need to make sure that the calculations when , Has been calculated .
Because the best route must meet 「 Monotone increasing 」, So we can use 「 Double pointer 」 Come on and Transfer at the same time , Each time the value is small, it will be updated , This ensures that the update process is also monotonous , That is, when it is necessary to calculate when , Than Small and Are transferred .
Code :
class Solution {
int MOD = (int)1e9 + 7;
public int maxSum(int[] nums1, int[] nums2) {
int n = nums1.length, m = nums2.length;
long[] f = new long[n + 1], g = new long[m + 1];
int i = 1, j = 1;
while (i <= n || j <= m) {
if (i <= n && j <= m) {
if (nums1[i - 1] < nums2[j - 1]) {
f[i] = f[i - 1] + nums1[i - 1];
i++;
} else if (nums2[j - 1] < nums1[i - 1]) {
g[j] = g[j - 1] + nums2[j - 1];
j++;
} else {
f[i] = g[j] = Math.max(f[i - 1], g[j - 1]) + nums1[i - 1];
i++; j++;
}
} else if (i <= n) {
f[i] = f[i - 1] + nums1[i - 1];
i++;
} else {
g[j] = g[j - 1] + nums2[j - 1];
j++;
}
}
return (int) (Math.max(f[n], g[m]) % MOD);
}
}
Time complexity : Spatial complexity :
Last
This is us. 「 Brush through LeetCode」 The first of the series No.1537 piece , The series begins with 2021/01/01, As of the start date LeetCode I have in common 1916 questions , Part of it is a locked question , We will finish all the questions without lock first .
In this series , In addition to explaining the idea of solving problems , And give the most concise code possible . If the general solution is involved, there will be corresponding code templates .
In order to facilitate the students to debug and submit code on the computer , I've built a warehouse :https://github.com/SharingSource/LogicStack-LeetCode .
In the warehouse address , You can see the links to the series 、 The corresponding code of the series 、LeetCode Links to the original problem and other preferred solutions .
More, more, more popular 「 written examination / interview 」 Relevant information can be accessed from the smart typesetting Gather new bases
边栏推荐
- Fine! Huawei firewall dual computer hot standby Technology: HRP, vgmp, VRRP
- Solution of intelligent all in one machine in expressway service area
- 打破内存墙的新利器成行业“热搜”!持久内存让打工人也能玩转海量数据+高维模型
- 运营商5G用户渗透远远比4G慢,5G的普及还得看中国广电
- 构建Go命令行程序工具链
- Database tools in intelij can connect but cannot display schema, tables
- 期货公司开户安全吗
- 如何轻松实现在线K歌房,与王心凌合唱《山海》
- [my advanced OpenGL learning journey] learning notes of OpenGL coordinate system
- Arrays API
猜你喜欢

Most common usage of vim editor

【云原生 | Kubernetes篇】Kubernetes基础入门(三)

MySQL binlog

存在安全隐患 部分冒险家混动版将召回

Database tools in intelij can connect but cannot display schema, tables

为什么企业实施WMS仓储管理系统很容易失败

如何扩展aws主机上的磁盘空间

运营商5G用户渗透远远比4G慢,5G的普及还得看中国广电

我与“Apifox”的网络情缘

Nifi from introduction to practice (nanny level tutorial) - environment
随机推荐
HMM to CRF understanding and learning notes
存在安全隐患 部分冒险家混动版将召回
Here comes Wi Fi 7. How strong is it?
Is it safe to open an account for flush stock on mobile phone!
[tke] multiple ingress controllers are used in the cluster
Flink Kubernetes Application部署
The first in China! Tencent cloud key management system passes password application verification test
clang: warning: argument unused during compilation: ‘-no-pie‘ [-Wunused-command-line-argument]
微信公众号调试与Natapp环境搭建
Parameterized tests guide in junit5
Three solutions for Jenkins image failing to update plug-in Center
[log service CLS] Tencent cloud log4j/logback log collection best practices
asciinema 搭配 asciicast2gif 实现高效的命令行终端录制能力
使用阿里云RDS for SQL Server性能洞察优化数据库负载-初识性能洞察
How to implement SQLSERVER database migration in container
Is it safe for futures companies to open accounts
Efficient tools commonly used by individuals
刚刚阿里面软件测试回来,3+1面任职阿里P7,年薪28*15薪
如何轻松实现在线K歌房,与王心凌合唱《山海》
日志记录真没你想的那么简单