Harry Potter And Spells

Harry made N Felix Felicis(Liquid Luck Potion), and there is an integer value for each N potion,X1,X2,X3.....XN

Harry recently came to know about a new spell by which he can multiply the Value of ith and (i+1)th potion by -1. where

1iN1. He can perform this spell any number of times. now he wants to maximize the total sum of all the potions. i.e find the maximum value of X1+X2+X3.....+XN after performing this spell any number of times.

Example:

Input:  n=5,arr[] = { 10, -4, -8, -11, 3 }
Output: 30

Approach

Java


public class HarryPotterAndSpells {
    public static void main(String[] args) {

        int n = 5;

        long sum = 0;
        long min = Integer.MAX_VALUE;
        int negCount = 0;
        int arr[] = { 10, -4, -8, -113 };

        for (int i = 0; i < n; i++) {
            long currentNum = arr[i];
            long currentNumAbs = Math.abs(currentNum);
            sum += currentNumAbs;

            min = Math.min(min, currentNumAbs);

            if (currentNum < 0) {
                negCount++;
            }
        }

        System.out.println(negCount % 2 == 0 ? sum : sum - 2 * min);
    }
}


No comments:

Post a Comment