Created
March 6, 2017 21:38
-
-
Save jianminchen/9f221d5c80a1068f693735714bbf16f9 to your computer and use it in GitHub Desktop.
Hackerrank - Lucky number 8 - study code using dynamic programming
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Text; | |
using System.Threading.Tasks; | |
namespace Hackerrank_LuckyNumber8_DP_Studycode | |
{ | |
/* | |
* Study dynamic programming solution | |
* | |
* questions on two things: | |
* first value is 1, count[0][0] = 1, why? | |
* second, count[n - 1][0] + Module - 1, why? | |
*/ | |
class Program | |
{ | |
public static long Module = 1000000007; | |
static void Main(string[] args) | |
{ | |
int n = Convert.ToInt32(Console.ReadLine()); | |
String number = Console.ReadLine().ToString(); | |
int[][] count = new int[n][]; // subsequences | |
for (int i = 0; i < n; i++) | |
{ | |
count[i] = new int[8]; | |
} | |
int SIZE = 8; | |
count[0][0] = 0; // ask why here? | |
count[0][(number[0] - '0') % SIZE]++; | |
// build a frequency table - | |
for (int i = 1; i < n; i++) | |
{ | |
// subseqences - just ignore the current elment | |
for (int remainder = 0; remainder < SIZE; remainder++) | |
{ | |
count[i][remainder] = count[i - 1][remainder]; | |
} | |
// iterate each element in the array - go over all possible remainders in ascending order | |
for (int remainder = 0; remainder < SIZE; remainder++) | |
{ | |
long current = count[i - 1][remainder]; | |
// if the remainder's related count is 0, then no possible subsequences to the nextRemainder | |
// skip the remainder. | |
if (current == 0) | |
{ | |
continue; | |
} | |
int nextRemainder = (10 * remainder + (number[i] - '0')) % SIZE; | |
count[i][nextRemainder] = (Int32)((count[i][nextRemainder] + current) % Module); | |
} | |
} | |
Console.WriteLine((count[n - 1][0] + Module - 1) % Module); | |
// Console.WriteLine((count[n - 1][0] + Module - 1) % Module); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment