Skip to content

Instantly share code, notes, and snippets.

@jianminchen
Created May 8, 2017 20:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jianminchen/4c443bdc2214a5ff0a4e3bfc2b31cd1c to your computer and use it in GitHub Desktop.
Save jianminchen/4c443bdc2214a5ff0a4e3bfc2b31cd1c to your computer and use it in GitHub Desktop.
Rookie3 codesprint - hackerrank - memorization, backtracking and backward processing - pass all test cases
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MaxScore_studyCode
{
/// <summary>
/// Try out the study code
/// Figure out things to do
/// </summary>
class Program
{
static void Main(string[] args)
{
ProcessInput();
//RunTestcase();
}
public static void ProcessInput()
{
int n = Convert.ToInt32(Console.ReadLine());
string[] data = Console.ReadLine().Split(' ');
long[] numbers = Array.ConvertAll(data, Int64.Parse);
long maxScore = GetMaxScore(numbers);
Console.WriteLine(maxScore);
}
public static void RunTestcase()
{
var array = new long[] { 4, 8, 5 };
var result = GetMaxScore(array);
}
public static long GetMaxScore(long[] numbers)
{
// Complete this function
return getMaxScore(new HashSet<long>(numbers), numbers.Sum());
}
static Dictionary<long, long> memo = new Dictionary<long, long>();
/// <summary>
/// backtracking, memorization, and also doing backward tracking.
/// Start from a subsequence with all elements are selected, then choose
/// last element from any number in the hashset, and then figure out the score.
/// </summary>
/// <param name="sequenceNumbers"></param>
/// <param name="sum"></param>
/// <returns></returns>
public static long getMaxScore(HashSet<long> sequenceNumbers, long sum)
{
if (memo.ContainsKey(sum))
{
return memo[sum];
}
var max = 0L; // using L stands for long
// go over all options for next number to remove
// backward tracking, assuming that all numbers are included,
// sum is original array's summation.
foreach (var number in sequenceNumbers.ToList())
{
sequenceNumbers.Remove(number);
var score = ((sum - number) % number) + getMaxScore(sequenceNumbers, sum - number);
sequenceNumbers.Add(number); // back tracking - add number back to the set
max = Math.Max(score, max);
}
memo[sum] = max;
return max;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment