Get the App
SLTechnology News&Howtos  ›  Development  › 

How to maximize the sum of arrays after K-times inversion by greedy algorithm

Shulou Source: shulou.com Published: 2022-06-03 01:44:28 09月19日 Update

This article mainly explains "how to maximize the array sum after K times inversion of greedy algorithm". Interested friends may wish to have a look at it. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn how to maximize the array sum after K-times inversion of the greedy algorithm.

Many recording friends have feedback on yesterday's topic: greedy algorithm: jumping game II is very difficult, so I am relieved, , because when I just explained greed, some recording friends will advise me: greed is not necessary to speak alone, just talk about moving rules. Many students should feel greedy. What's so hard about it? Now we can find that although the truth of greed is simple, it is very clever to solve problems, and there is no difference in difficulty.

Today is a simple problem, the key is to cultivate greedy problem-solving ideas!

Given an integer array A, we can only modify the array by selecting an index I and replacing A [I] with-A [I], and then repeat the process K times in total. (we can select the same index I multiple times.)

After modifying the array in this way, the largest possible sum of the array is returned.

Example 1: input: a = [4jin2jin3], K = 1

Output: 5

Explanation: select the index (1,), and then A becomes [4mai Yu 2jue 3].

Example 2:

Input: a = [3mai Mei 1JI 0JI 2], K = 3

Output: 6

Explanation: select the index (1, 2, 2), and then A becomes [3meme1p0Pol 2].

Example 3:

Input: a = [2, 5, 5, 4], K = 2

Output: 13

Explanation: select the index (1, 4), and then A becomes [2, 3, 4, 1, 5, 5, 4].

Tip:

one

Tags: Array maximum algorithm idea index selection numeric integer local positive example absolute negative interpretation input output minimum together global content Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno MySQL Linux Shulou Information Xiaomi Redmi