Skip to content

Instantly share code, notes, and snippets.

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/ebf53cc603ec48d24f5f214543ed6c03 to your computer and use it in GitHub Desktop.
Save jianminchen/ebf53cc603ec48d24f5f214543ed6c03 to your computer and use it in GitHub Desktop.
Max Score - Rookie 3 - forward processing, memorization, score 14 out of 30, timeout test cases from 7 - 10
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MaxScore
{
/// <summary>
/// Backtracking, memorization, forward handling
/// What is the key? Given the sum, what is the biggest score from those sum.
/// </summary>
class Program
{
static void Main(string[] args)
{
ProcessInput();
//RunTestcase();
}
public static void RunTestcase()
{
int n = 3;
long[] a = new long[] { 4, 8, 5 };
var used = new HashSet<int>();
IList<int> sequence = new List<int>();
long sum = 0;
var calculated = new Dictionary<long, long>();
long maxScore = GetMaxScore(a, used, sum, 0, sequence, calculated);
Console.WriteLine(maxScore);
}
public static void ProcessInput()
{
int n = Convert.ToInt32(Console.ReadLine());
string[] a_temp = Console.ReadLine().Split(' ');
long[] a = Array.ConvertAll(a_temp, Int64.Parse);
var used = new HashSet<int>();
IList<int> sequence = new List<int>();
long sum = 0;
Dictionary<long, long> calculated = new Dictionary<long, long>();
long maxScore = GetMaxScore(a, used, sum, 0, sequence, calculated);
Console.WriteLine(maxScore);
}
/// <summary>
///
/// </summary>
/// <param name="array"></param>
/// <returns></returns>
public static long GetMaxScore(long[] array, HashSet<int> used, long sum, long score, IList<int> sequence, Dictionary<long, long> calculated)
{
if (used.Count == array.Length)
{
return 0;
}
long maxScore = long.MinValue;
long total = array.Sum();
for (int i = 0; i < array.Length; i++)
{
if (used.Contains(i)) continue;
long current = array[i];
var currentScore = sum % current;
var newCopy = new HashSet<int>(used);
newCopy.Add(i);
var newSequence = new List<int>(sequence);
newSequence.Add(i);
var lookup = total - sum - current;
if (calculated.ContainsKey(lookup))
{
currentScore += calculated[lookup];
}
else
{
long value = GetMaxScore(array, newCopy, sum + current, score + currentScore, newSequence, calculated);
currentScore += value;
calculated.Add(lookup, value);
}
maxScore = (currentScore > maxScore) ? currentScore : maxScore;
}
return maxScore;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment