[贪心] leetcode 1144 Decrease Elements To Make Array Zigzag

problem:https://leetcode.com/contest/weekly-contest-148/problems/decrease-elements-to-make-array-zigzag/

        Greedy title. There are two possible zigzag, a maximum value index is odd, an even index is a maximum. The smallest possible number decrease, respectively, calculated on these two cases.

        For a [i]> = a [i-1], if you want a [i] <a [i-1], such that a [i] = a [i-1] - 1 to.

        The following is the code during the competition, where there may be streamlined:

        (This question is not easy start it, how suddenly become a medium)

class Solution {
public:
    int movesToMakeZigzag(vector<int>& nums) {
        
        int oddMax = 0;
        vector<int> oddNums(nums);
        for(int i = 1;i < oddNums.size();i++)
        {
            if(i % 2)
            {
                if(oddNums[i] <= oddNums[i - 1])
                {
                    oddMax += (oddNums[i - 1] - oddNums[i]) + 1;
                    oddNums[i - 1] = oddNums[i] - 1;
                }
            }
            else 
            {
                if(oddNums[i] >= oddNums[i - 1])
                {
                    oddMax += (oddNums[i] - oddNums[i - 1]) + 1;
                    oddNums[i] = oddNums[i - 1] - 1;
                }               
            }
        }
        int evenMax = 0;
        vector<int> evenNums(nums);
        for(int i = 1;i < evenNums.size();i++)
        {
            if(i % 2)
            {
                if(evenNums[i] >= evenNums[i - 1])
                {
                    evenMax += (evenNums[i] - evenNums[i - 1]) + 1;
                    evenNums[i] = evenNums[i - 1] - 1;
                }
            }
            else 
            {
                if(evenNums[i] <= evenNums[i - 1])
                {
                    evenMax += (evenNums[i - 1] - evenNums[i]) + 1;
                    evenNums[i - 1] = evenNums[i] - 1;
                }               
            }           
        }
   //     cout << oddMax << " " << evenMax << endl;
        return min(oddMax, evenMax);
    }
};

 

Guess you like

Origin www.cnblogs.com/fish1996/p/11297968.html