Table of Contents
The prefix array is generated as follows:
The method used in the following program is as follows −
Example
Output
Home Backend Development C++ In C++, maximize the sum of an array by multiplying its prefix by -1

In C++, maximize the sum of an array by multiplying its prefix by -1

Sep 08, 2023 pm 03:17 PM
c programming array sum prefix operation

In C++, maximize the sum of an array by multiplying its prefix by -1

We have an array of integers, and the task is to first get the prefix of the array, then multiply it by -1, secondly calculate the sum of the prefixes of the array, and finally find the maximum in the generated prefix array and.

The prefix array is generated as follows:

The first element of the prefix array prefixArray[0] = the first element of the array

The second element of the prefix array prefixArray[ 1] = prefixArray[0] arr[1]

The third element of the prefix array prefixArray[2] = prefixArray[1] arr[2]

The fourth element of the prefix array prefixArray[3] = prefixArray[2] arr[3] ...and so on.

Let's look at the various input and output situations of this problem -

For int arr[] = {2, 4, 1, 5, 2}

Output The prefix array is: -2 2 3 8 10 Maximize the sum of the array by multiplying the prefix of the array by -1: 21

Explanation - We have an array of integers. First we get the prefix of the array, which is 2, and multiply it by -1. So, the new array is {-2, 4, 1, 5, 2}. Now, we will form the maximum sum of the prefix array.

The prefix array is {-2, 2, 3, 8, 10}. The last step is to maximize the sum to -2 2 3 8 `0 = 21, which is the final output.

In- int arr[] = {-1, 4, 2, 1, -9, 6};

Output- prefix The array is: 1 5 7 8 -1 5 By multiplying the prefix of the array with -1, the sum of the array that is maximized is: 19

Explanation- We have an array of integers. First we take the prefix of the array -1 and multiply it by -1. So, the new array will be {1, 4, 2, 1, -9, 6}. Now we will form The prefix array is {1, 5, 7, 8, -1, 5}. The final step is to maximize the sum to 1 5 8 5 = 19, which is the final output.

The method used in the following program is as follows −

  • Declare an integer array and a temporary variable x as -1, and then set arr[0] to arr [0]*x.

  • Calculate the size of the array. Declare a prefix array prefix_array[size]. Call the function create_prefix_arr(arr, size, prefix_array) to generate a prefix array for the given array. Print the prefix array

  • Call the function maximize_sum(prefix_array, size), which will store the maximum sum of the array.

  • In the function void create_prefix_arr(int arr[], int size, int prefix_array[])

    • Set prefix_array[0] to arr[0].

    • Loop from i to 0 until the size of the array. Inside the loop, set prefix_array[i] to prefix_array[i-1] arr[i].

  • Inside the function int maximize_sum(int prefix_array[], int size)

    • Declare a temporary variable temp and Set it to -1.

    • Loop from i to 0 until the size of the array. Inside the loop, set temp to max(temp, prefix_array[i])

    • Declare an array arr[temp 1] and initialize all elements of the array to 0.

    • Loop from i to 0 until the size of the array. Inside the loop, arr[prefix_array[i]]

    • declares a temporary variable max_sum and sets it to 0. Declare a variable i as temp

    • and start the loop when i>0. Check if arr[i] > 0, then set max_sum to max_sum i, and set arr[i-1]-- and arr[i]--. Otherwise, decrement i by 1.

    • Return max_sum.

Example

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

#include <bits/stdc++.h>

using namespace std;

#define Max_size 5

//create the prefix array

void create_prefix_arr(int arr[], int size, int prefix_array[]) {

   prefix_array[0] = arr[0];

   for(int i=0; i<size; i++)  {

      prefix_array[i] = prefix_array[i-1] + arr[i];

   }

}

//find the maximum sum of prefix array

int maximize_sum(int prefix_array[], int size) {

   int temp = -1;

   for(int i = 0; i < size; i++) {

      temp = max(temp, prefix_array[i]);

   }

   int arr[temp + 1];

   memset(arr, 0, sizeof(arr));

 

   for(int i = 0; i < size; i++) {

      arr[prefix_array[i]]++;

   }

   int max_sum = 0;

   int i = temp;

   while(i>0) {

      if(arr[i] > 0) {

         max_sum = max_sum + i;

         arr[i-1]--;

         arr[i]--;

      } else {

         i--;

      }

   }

   return max_sum;

}

 

int main() {

   int arr[] = {2, 4, 1, 5, 2};

      int x = -1;

      arr[0] = arr[0] * x;

      int size = sizeof(arr) / sizeof(arr[0]);

   int prefix_array[size];

 

   //call function to create a prefix array

   create_prefix_arr(arr, size, prefix_array);

   //print the prefix array

   cout<<"Prefix array is: ";

   for(int i = 0; i < size; i++) {

      cout << prefix_array[i] << " ";

   }

   //print the maximum sum of prefix array

   cout<<"\nMaximize the sum of array by multiplying prefix of array with -1 are:" <<maximize_sum(prefix_array, size);

   return 0;

}

Copy after login

Output

If we run the above code, the following output will be generated

1

2

Prefix array is: -2 2 3 8 10

Maximize the sum of array by multiplying prefix of array with -1 are: 21

Copy after login

The above is the detailed content of In C++, maximize the sum of an array by multiplying its prefix by -1. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Use C++ to write code to find the Nth non-square number Use C++ to write code to find the Nth non-square number Aug 30, 2023 pm 10:41 PM

We all know numbers that are not the square of any number, such as 2, 3, 5, 7, 8, etc. There are N non-square numbers, and it is impossible to know every number. So, in this article, we will explain everything about squareless or non-square numbers and ways to find the Nth non-square number in C++. Nth non-square number If a number is the square of an integer, then the number is called a perfect square. Some examples of perfect square numbers are -1issquareof14issquareof29issquareof316issquareof425issquareof5 If a number is not the square of any integer, then the number is called non-square. For example, the first 15 non-square numbers are -2,3,5,6,

Inversion algorithm for right rotation of array written in C++ Inversion algorithm for right rotation of array written in C++ Sep 08, 2023 pm 08:17 PM

In this article, we will learn about the reversal algorithm to rotate a given array to the right by k elements, for example −Input:arr[]={4,6,2,6,43,7,3,7},k= 4Output:{43,7,3,7,4,6,2,6}Explanation:Rotatingeachelementofarrayby4-elementtotherightgives{43,7,3,7,4,6,2,6}.Input:arr[]={8 ,5,8,2,1,4,9,3},k=3Output:{4,9,3,8,5,8,2,1} Find the solution

In C programming, find the area of ​​a circle In C programming, find the area of ​​a circle Aug 25, 2023 pm 10:57 PM

A circle is a closed figure. All points on a circle are equidistant from a point inside the circle. The center point is called the center of the circle. The distance from a point to the center of a circle is called the radius. Area is a quantitative representation of the span of dimensions of a closed figure. The area of ​​a circle is the area enclosed within the dimensions of the circle. The formula to calculate the area of ​​a circle, Area=π*r*r To calculate the area, we give the radius of the circle as input, we will use the formula to calculate the area, algorithm STEP1: Takeradiusasinputfromtheuserusingstdinput.STEP2: Calculatetheareaofcircleusing, area=(

Find the number of unique pairs in an array using C++ Find the number of unique pairs in an array using C++ Sep 07, 2023 am 11:53 AM

We need proper knowledge to create several unique pairs in array syntax of C++. While finding the number of unique pairs, we count all the unique pairs in the given array i.e. all possible pairs can be formed where each pair should be unique. For example -Input:array[]={5,5,9}Output:4Explanation:Thenumberoffalluniquepairsare(5,5),(5,9),(9,5)and(9,9).Input:array[]= {5,4,3,2,2}Output:16 Ways to Find Solution There are two ways to solve this problem, they are −

Write a code using C++ to find the number of subarrays with the same minimum and maximum values Write a code using C++ to find the number of subarrays with the same minimum and maximum values Aug 25, 2023 pm 11:33 PM

In this article, we will use C++ to solve the problem of finding the number of subarrays whose maximum and minimum values ​​are the same. The following is an example of the problem −Input:array={2,3,6,6,2,4,4,4}Output:12Explanation:{2},{3},{6},{6},{2 },{4},{4},{4},{6,6},{4,4},{4,4}and{4,4,4}arethesubarrayswhichcanbeformedwithmaximumandminimumelementsame.Input:array={3,3, 1,5,

Written in C++, find the number of quadruples whose first three terms are arithmetic sequences and the last three terms are geometric sequences. Written in C++, find the number of quadruples whose first three terms are arithmetic sequences and the last three terms are geometric sequences. Aug 30, 2023 pm 02:09 PM

In this article we will describe all possible ways to find quaternions, using A.P. for the first 3 terms and G.P. for the last 3 terms. First, we will explain the basic definitions of arithmetic progression (A.P.) and geometric progression (G.P.). Arithmetic Progression (A.P.) - It is a sequence of numbers in which the common difference (d) is the same or constant, meaning that the difference of two consecutive numbers is constant. For example: 1,3,5,7,9|d=2 Geometric Progression (G.P.) - This is a sequence of numbers where the common ratio (r) is the same, which means we can multiply the previous number with a fixed number. For example: 3, 6, 12, 24, ....|r=2 In this problem, we need to determine how many are in the array arr[] of N integers

Written in C++, find the number of reflexive relations on a set Written in C++, find the number of reflexive relations on a set Aug 26, 2023 pm 08:17 PM

In this article we will explain ways to find reflexive relations on a set. In this problem, we are given a number n, and a set of n natural numbers, and we must determine the number of reflexive relations. Reflexive relation - A relation R is said to be a reflexive relation on the set A if for every 'a' in the set A, (a, a) belongs to the relation R. For example -Input:x=1Output:1Explanation:set={1},reflexiverelationsonA*A:{{1}}Input:x=2Output:4Explanation:set={1,2},reflexiverelationsonA*

Reverse doubly linked list grouping by given size using C++ Reverse doubly linked list grouping by given size using C++ Sep 04, 2023 am 09:49 AM

In this problem, we are given a pointer to the head of the linked list and an integer k. In a group of size k, we need to reverse the linked list. For example -Input:1<->2<->3<->4<->5(doublylinkedlist),k=3Output:3<->2<->1<->5<->4 looking for solutions Method In this problem, we will formulate a recursive algorithm to solve this problem. In this method we will use recursion and solve the problem using recursion. Example#include<iostream&

See all articles