Adding Minimum Elements in a Sequence

I have a certain number of triplets, and I want to add numbers so that the amount remains minimal, and you can choose only one number in a particular triplet. eg:

10 10 1   //minimum 1
1  10 21  //minimum 1
10 1  10  //minimum 1 Ans : 1+1+1 = 3

However, you cannot select an adjacent element in the same column.

10 10 1 //select 1
10 10 1 //cannot select 1, that adjacent!
10 10 1 //safe to select 1

But the problem is that in the case of communication, I need to scan the next triplet in the sequence and not select the number in the previous sequence to get the maximum profit, for example:

10 10 10  // step 2.select 10 from column 1 or 2
10 10 1   // step 1.make sure not to select element in column 3 in previous sequence
          // step 3. select 1 from column 3

Since we cannot replace the scanner position, so I cannot move the readLine scanner to the previous position, how can I check in advance?

My take: (Since the range of numbers is large, I use BigInt)

for(long j=0; j<noOfTriples ; j++){
    firstNumber = in.nextBigInteger();
    secNumber = in.nextBigInteger();
    thirdNumber = in.nextBigInteger();

    if(areEqual(firstNumber, secNumber, thirdNumber)){
        while(true){
             firstNumber2 = in.nextBigInteger();
             secNumber2 = in.nextBigInteger();
             thirdNumber2 = in.nextBigInteger();
             noOfTriples--;
                if(areEqual(firstNumber2, secNumber2, thirdNumber2)){
                    count.add(secNumber2); // add any number to the count
                                          // since all of them are same
                }else
                    break;
                }   

    pass(firstNumber, secNumber, thirdNumber, least(firstNumber2, secNumber2, thirdNumber2));
    //pass adds up the minimum of three to the count 
    //where the last field indicates which element to NOT use while adding &
    //least returns minimum of the three
    }else
    pass(firstNumber, secNumber, thirdNumber, -1);  //-1 indicates no bias
}

Edit:

+4
2

, .

F (idx, prev), idx , , prev , . , F (idx + 1, new_prev), new_prev . :

F(idx, prev) {

     if ( idx == n+1 ) return 0; //Done with shopping on all N triplets

     ans = INFINITY

     for all item_nums from 1 to 3
            if ( item_nums != prev ) ans = min(ans, cost of item_num in shop_num idx + F(idx+1, item_nums)

    return ans
}
+2

, , , , , . . (9, 3, 5), (8, 4, 7), (6, 1, 8), , , 5 4. , , 7 3, 1. , , , .

, . , , . , , :

, List<List<Integer>>.

int minSum(int index, int previous, List<List<Integer>> inputs) {
    if (index >= inputs.size())
        return 0;
    else
        return IntStream.range(0, 3)
            .filter(n -> n != previousIndex)
            .map(n -> minSum(index + 1, n, inputs)).min();
}

, Java 8 .

, . , , , .

, (1, 8, 5), (2, 3, 6), (4, 9, 2). 1 + 3 + 4 7. , , - 8 . , , , (.. 7), , , .

, . , , .

+1

Source: https://habr.com/ru/post/1613763/


All Articles