[Algorithm] DP
Posted Answer1215
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[Algorithm] DP相关的知识,希望对你有一定的参考价值。
Write a function that takes in an array of positive integers and returns the maximum sum of non-adjacent elements in the array.
If the input array is empty, the function should return 0.
Sample Input
array = [75, 105, 120, 75, 90, 135]
Sample Output
330 // 75 + 120 + 135
Normal approach:
// Time: O(N)
// Space: O(N)
function maxSubsetSumNoAdjacent(array)
if (array.length === 0)
return 0
const dp = Array.from(array, (val, i) =>
if (i === 0)
return val
else if (i === 1)
return Math.max(array[0], array[1])
else
return 0
)
for (let i = 2; i < array.length; i++)
if (dp[i-2] + array[i] > dp[i-1])
dp[i] = dp[i-2] + array[i]
else
dp[i] = dp[i-1]
return dp[dp.length - 1]
// Do not edit the line below.
exports.maxSubsetSumNoAdjacent = maxSubsetSumNoAdjacent;
It can be improved to:
// Time: O(N)
// Space: O(1)
We don\'t need to track the whole dp
array, and loop from beginning to current i
position to get max sum.
What we can do for this task is that we only need to keep tracking two values, a samll slice window.
if ary[i] + dp[0] > dp[1]
dp[0] = dp[1]
dp[1] = ary[i] + dp[0]
else
dp[0] = dp[1]
function maxSubsetSumNoAdjacent(array)
if (array.length === 0)
return 0
const dp = [0, 0]
for (let i = 0; i < array.length; i++)
if (dp[0] + array[i] > dp[1])
const val = dp[0] + array[i]
dp[0] = dp[1]
dp[1] = val
else
dp[0] = dp[1]
return dp[1]
// Do not edit the line below.
exports.maxSubsetSumNoAdjacent = maxSubsetSumNoAdjacent;
数位dp
//hdu2089 #include "cstdio" #include "cstring" #include "iostream" #include "algorithm" using namespace std; int cont; long long dig[10001]; long long dp[20][2][2]; int dfs(int pos,int six,int flag){ if (pos<0)return 1; long long ans=0; if (dp[pos][six][flag]!=-1)return dp[pos][six][flag]; for (int i = 0; i <= 9;i++){ if (i>dig[pos]&&flag==1)break; if (i==2&&six==1)continue; if (i==4)continue; ans=ans+dfs(pos-1,i==6,flag&&i==dig[pos]); } return dp[pos][six][flag]=ans; } long long s(long long x){ if (x<0)return 0; memset(dp,-1,sizeof(dp)); cont=0; while (x){ dig[cont++]=x%10; x=x/10; } return dfs(cont-1,0,1); } int main (){ long long n , m; while (~scanf ("%lld%lld",&n,&m)){ if (n==0&&m==0)break; printf ("%lld ",s(m)-s(n-1)); } }
以上是关于[Algorithm] DP的主要内容,如果未能解决你的问题,请参考以下文章