Gqrsw
Gqrsw

Reputation: 11

MaximizeSum - determining the maximum possible total of points

The results are good, but the program is written inefficiently - it is not possible to sum even 100 items.

Does anybody have an idea how to improve this?

when the vector / group of numbers of the variable "sequence" is too large, the program takes a long time, the goal is to make it count quickly

example

 public interface ISolver<T>
    {
        Task<T> SolveAsync(IEnumerable<T> sequence);
    }

    public class Solver : ISolver<short>
    {
        private async Task<short> MaximizeSumAsync(IEnumerable<short> sequence, short tripleSum = 0)
        {
            if (sequence.Count() == 3)
                return (short)(sequence.Sum(x => x) + tripleSum);
            var tasks = new List<Task<short>>();
            for (short i = 1; i < sequence.Count() - 1; i++)
            {
                // better option?
                tasks.Add(MaximizeSumAsync(sequence.RemoveAt(i), (short)(tripleSum + sequence.Sum((short)(i - 1), (short)(i + 1)))));
            }
            await Task.WhenAll<short>(tasks);
            return tasks.Select(x => x.Result).Max();
        }
        public async Task<short> SolveAsync(IEnumerable<short> sequence)
        {
            return await MaximizeSumAsync(sequence);
        }

        public static short Sum(this IEnumerable<short> sequence, short startIndex, short endIndex)
        {
            if (startIndex < 0)
                throw new IndexOutOfRangeException();

            if (endIndex >= sequence.Count())
                throw new IndexOutOfRangeException();

            short res = 0;

            for (short i = startIndex; i <= endIndex; i++)
                res += sequence.ElementAt(i);

            return res;
        }
        public static IEnumerable<T> RemoveAt<T>(this IEnumerable<T> sequence, short index)
        {
            if (index < 0 || index > sequence.Count() - 1)
                throw new IndexOutOfRangeException($"Index {index} is larger than the number of elements in sequence ({sequence.Count()}).");

            if (index == 0)
                return sequence.Skip(1);

            if (index == sequence.Count() - 1)
                return sequence.Take(sequence.Count() - 1);

            var part1 = sequence.Take(index);
            var part2 = sequence.Skip(index + 1);

            return part1.Concat(part2);
        }

maybe some alternative for linq?

Upvotes: 0

Views: 40

Answers (0)

Related Questions