5214. longest sequence given difference

  This question, more interesting, they say a lot better with c ++ will be the Map, but also saves space, but since I do not ah (fellow interested, and self-realization).

 

 

  A recurrence of the problem, because t is not c ++'s Map so I can use arrays to implement, but have a negative ah, ah array index can not be negative, how this can do the cool. Simple methods of violence, direct plus the maximum boundary value, an array of open twice as large, equivalent to remove the symbol. This time we can out of our array of dp. Since it is recursive then you have to have a recurrence formula. It is also very simple, the longest Han Han Han is not that relationship again and again in steps of accumulated 1? But also the longest, you certainly had to have a max function. We set DP [i] represents the current sequence number is the last subsequence i is the maximum length, each time we i ++ after the previous time that the "maximum value" for comparison, if the intermediate disconnected, then since the last " the maximum value of "index determined by step, in steps of a fixed value, it will automatically disconnect the recount. We have this rule can very easily write the state transition equation :

dp[i]=max(dp[i],dp[i-difference]+1);

  Of course, this is just the dynamic transfer equation, still need to implement specific changes. How we can own to try to achieve, and then look at the code.

. 1  / * *
 2  * @brief longest sequence given difference
 . 3  * @note must add 10000 
 . 4  * @param ARR: in a given sequence
 . 5  * @param arrSize: sequence length
 . 6  * @param -difference: Solid fixed difference
 7  * Zhen Yang @author small fans brother 
 . 8   * / 
. 9  int longestSubsequence ( int * ARR, int arrSize, int -difference) {
 10      int ANS = 0 ;
 . 11      int DP [ 20002 ] = { 0 };
 12 is      for ( int I = 0; i < arrSize; i++)
13     {
14         arr[i] += 10000;
15     }
16     
17     for (int i = 0; i < arrSize; i++)
18     {
19         int sum = arr[i] - difference;
20         if (sum > 20000 || sum < 0)
21         {
22             dp[arr[i]] = 1;
23         }
24         else
25         {
26             dp[arr[i]] = dp[arr[i]] > (dp[sum]+1) ? dp[arr[i]] : (dp[sum]+1);
27         }
28         ans = ans > dp[arr[i]] ? ans : dp[arr[i]];
29         printf("%d\n", ans);
30     }
31     
32     return ans;
33 }
View Code

  Race week is not easy, gentlemen encourage each other!

Guess you like

Origin www.cnblogs.com/daker-code/p/11627391.html