C# subtract list from number in all possible ways so the resultant number is bigger than 0

1.7k views Asked by At

I need to subtract list from a number, so the resultant number will be equal or bigger than 0 with a smallest result possible. Also I need to see which items of the list were subtracted.

int a = 10;
List<int> list = new List<int>();

I've tried this (probably really bad idea):

for (int c = 0; c < list.Count; c++)
{
    if (a > 0)
    {
        a = a - list.ElementAt(c);

        if (a < 0)
        {
            a = a + list.ElementAt(c);
        }
        else
        {
            Console.Write("{0}", list.ElementAt(c));
        }
    }
}

But the problem is that it only subtract in one way and doesn't find the best option.

Thanks for any ideas.

1

There are 1 answers

0
Habib On

I believe the OP is looking to find smallest possible result after subtraction, but that result has to be greater than or equal to zero.

For example, in case of {13, 12, 11, 9} and the given number being 10 the result after subtraction should be {3,2,1,-1} for each list item respectively, in that case the final result should be 1 as it is minimum value, but greater than or equal to zero.

In that case the code could look like:

int a = 10;
List<int> list = new List<int> {13, 12, 11, 9};


int min = -1;
for (int c = 0; c < list.Count; c++)
{
    int tempResult = list[c] - a;
    if (tempResult >= 0)
    {
        min = tempResult;
    }
}

Console.WriteLine(min);