Mitchel  Carter

Mitchel Carter

1597741200

Maximize the last Array element as per the given conditions - GeeksforGeeks

Given an array arr[] consisting of N integers, rearrange the array such that it satisfies the following conditions:

arr[0] must be 1.
Difference between adjacent array elements should not exceed 1, that is, arr[i] – arr[i-1] ≤ 1 for all 1 ≤ i < N.
The permissible operations are as follows:

Rearrange the elements in any way.
Reduce any element to any number ≥ 1.
The task is to find the maximum possible value that can be placed at the last index of the array.

Examples:

Input: arr[] = {3, 1, 3, 4}
Output: 4
Explanation:
Subtracting 1 from the first element modifies the array to {2, 1, 3, 4}.
Swapping the first two elements modifes the array to {1, 2, 3, 4}.
Therefore, maximum value placed at the last index is 4.

Input: arr[] = {1, 1, 1, 1}
Output: 1

Approach:
To solve the given problem, sort the given array and balance it according to the given condition starting from left towards right. Follow the below steps to solve the problem:

Sort the array in ascending order.
If the first element is not 1, make it 1.
Traverse the array over the indices [1, N – 1) and check if every adjacent element has a difference of ≤ 1.
If not, decrement the value till the difference becomes ≤ 1.
Return the last element of the array.
Below is the implementation of above problem:

filter_none
edit
play_arrow

brightness_4
// C++ Program to implement
// the above approach
#include <bits/stdc++.h>
using namespace std;

// Function to find the maximum possible value
// that can be placed at the last index
int maximizeFinalElement(int arr[], int n)
{
// Sort array in ascending order
sort(arr, arr + n);

// If the first element 
// is not equal to 1 
if (arr[0] != 1) 
    arr[0] = 1; 

// Traverse the array to make 
// difference between adjacent 
// elements <=1 
for (int i = 1; i < n; i++) { 
    if (arr[i] - arr[i - 1] > 1) { 
        arr[i] = arr[i - 1] + 1; 
    } 
} 
return arr[n - 1]; 

}

// Driver Code
int main()
{
int n = 4;
int arr[] = { 3, 1, 3, 4 };

int max = maximizeFinalElement(arr, n); 
cout << max; 

return 0; 

}
Output:
4
Time Complexity: O(NlogN)
Auxiliary Space: O(N)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

#arrays #greedy #mathematical #sorting #array-rearrange #carwale

What is GEEK

Buddha Community

Maximize the last Array element as per the given conditions - GeeksforGeeks
Mitchel  Carter

Mitchel Carter

1597741200

Maximize the last Array element as per the given conditions - GeeksforGeeks

Given an array arr[] consisting of N integers, rearrange the array such that it satisfies the following conditions:

arr[0] must be 1.
Difference between adjacent array elements should not exceed 1, that is, arr[i] – arr[i-1] ≤ 1 for all 1 ≤ i < N.
The permissible operations are as follows:

Rearrange the elements in any way.
Reduce any element to any number ≥ 1.
The task is to find the maximum possible value that can be placed at the last index of the array.

Examples:

Input: arr[] = {3, 1, 3, 4}
Output: 4
Explanation:
Subtracting 1 from the first element modifies the array to {2, 1, 3, 4}.
Swapping the first two elements modifes the array to {1, 2, 3, 4}.
Therefore, maximum value placed at the last index is 4.

Input: arr[] = {1, 1, 1, 1}
Output: 1

Approach:
To solve the given problem, sort the given array and balance it according to the given condition starting from left towards right. Follow the below steps to solve the problem:

Sort the array in ascending order.
If the first element is not 1, make it 1.
Traverse the array over the indices [1, N – 1) and check if every adjacent element has a difference of ≤ 1.
If not, decrement the value till the difference becomes ≤ 1.
Return the last element of the array.
Below is the implementation of above problem:

filter_none
edit
play_arrow

brightness_4
// C++ Program to implement
// the above approach
#include <bits/stdc++.h>
using namespace std;

// Function to find the maximum possible value
// that can be placed at the last index
int maximizeFinalElement(int arr[], int n)
{
// Sort array in ascending order
sort(arr, arr + n);

// If the first element 
// is not equal to 1 
if (arr[0] != 1) 
    arr[0] = 1; 

// Traverse the array to make 
// difference between adjacent 
// elements <=1 
for (int i = 1; i < n; i++) { 
    if (arr[i] - arr[i - 1] > 1) { 
        arr[i] = arr[i - 1] + 1; 
    } 
} 
return arr[n - 1]; 

}

// Driver Code
int main()
{
int n = 4;
int arr[] = { 3, 1, 3, 4 };

int max = maximizeFinalElement(arr, n); 
cout << max; 

return 0; 

}
Output:
4
Time Complexity: O(NlogN)
Auxiliary Space: O(N)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

#arrays #greedy #mathematical #sorting #array-rearrange #carwale

Houston  Sipes

Houston Sipes

1598014800

Rearrange Array to maximize number having Array elements

Given an array of integers arr[] and a binary string str of length N, the task is to rearrange given array by swapping array elements from indices having the same character in the string, such that the number formed by the elements of the rearranged array as digits is the maximum possible.

Examples:

Input:_ arr[]={1, 3, 4, 2}, str=”0101”_

Output:_ 4 3 1 2_

Explanation:

Since arr[0] is less than arr[2], so swap them. Therefore the maximum possible number from the array is 4, 3, 1, 2.

Input:_ arr[] = { 1, 3, 456, 6, 7, 8 }, str = “101101”_

Output:_ 8 7 6 456 3 1_

Explanation:

Array elements present at 0-chractered indices: {3, 7}

Largest number that can be formed from the above two numbers is 73

Array elements present at 1-chractered indices: {1, 456, 6, 8}

Largest number that can be formed from the above two numbers is 864561

Therefore, maximum number that can be generated from the array is 87645631

Approach: Follow the steps below to solve the problem:

  1. Create two arrays to store 0-charactered index elements and 1-charactered index elements from the array.
  2. Sort the arrays to form largest possible numbers from these two arrays.
  3. Iterate over str and based on the characters, place array elements from the sorted arrays.

Below is the implementation of the above approach:

  • C++

// C++ Program to implement

// the above approach

#include <bits/stdc++.h>

**using** **namespace** std;

// Comparison Function to sort()

**int** myCompare(``**int** a, **int** b)

{

string X = to_string(a);

string Y = to_string(b);

// Append Y at the end of X

string XY = X.append(Y);

// Append X at the end of Y

string YX = Y.append(X);

// Compare and return greater

**return** XY.compare(YX) < 0 ? 1 : 0;

}

// Function to return the rearranged

// array in the form of largest

// possible number that can be formed

**void** findMaxArray(vector<``**int**``>& arr, string& str)

{

**int** N = arr.size();

vector<``**int**``> Z, O, ans(N);

**for** (``**int** i = 0; i < N; i++) {

**if** (str[i] == '0'``) {

Z.push_back(arr[i]);

}

**else** {

O.push_back(arr[i]);

}

}

// Sort them in decreasing order

sort(Z.rbegin(), Z.rend(), myCompare);

sort(O.rbegin(), O.rend(), myCompare);

**int** j = 0, k = 0;

// Generate the sorted array

**for** (``**int** i = 0; i < N; i++) {

**if** (str[i] == '0'``) {

ans[i] = Z[j++];

}

**else** {

ans[i] = O[k++];

}

}

**for** (``**int** i = 0; i < N; i++) {

cout << ans[i] << " "``;

}

}

// Driver Code

**int** main()

{

vector<``**int**``> arr = { 1, 3, 456, 6, 7, 8 };

string str = "101101"``;

findMaxArray(arr, str);

**return** 0;

}

Output:

8 7 6 456 3 1

Time Complexity:_ O(NlogN)_

Auxiliary Space:_ O(N)_

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

#arrays #mathematical #sorting #array-rearrange

Joseph  Murray

Joseph Murray

1623911281

How to Print an Array in Java

Introduction

Printing an array is a quick way to give us visibility on the values of the contents inside. Sometimes the array values are the desired output of the program.

In this article, we’ll take a look at how to print an array in Java using four different ways.

While the “best way” depends on what your program needs to do, we begin with the simplest method for printing and then show more verbose ways to do it.

#java #array #how to print an array in java #array in java #print an array in java #print

Brain  Crist

Brain Crist

1596627360

Minimum count of elements required to obtain the given Array

Given an array arr[] consisting of N integers, the task is to find the array K[] of minimum possible length such that after performing multiple mirror operations on K[], the given array arr[] can be obtained.

Mirror Operation:_ Appending all the array elements to the original array in reverse order._

Illustration:

arr[] = {1, 2, 3}

After 1st mirror operation, arr[] modifies to {1, 2, 3, 3, 2, 1}

After 2nd mirror operation, arr[] modifies to {1, 2, 3, 3, 2, 1, 1, 2, 3, 3, 2, 1}

Examples:

Input:_ N = 6, arr[] = { 1, 2, 3, 3, 2, 1 }_

Output:_ 3_

Explanation:

Subarrays {1, 2, 3} and {3, 2, 1} are mirror images of each other.

Single mirror operation on {1, 2, 3} obtains the given array.

Therefore, the minimum number of elements required is 3.

Input:_ N = 8, arr[] = { 1, 2, 2, 1, 1, 2, 2, 1 }_

Output:_ 2_

Explanation:

Subarrays {1, 2, 2, 1} and {1, 2, 2, 1} are mirror images of each other.

Subarray {1, 2} and {2, 1} are mirror images of each other.

{1, 2} -> {1, 2, 2, 1} -> {1, 2, 2, 1, 1, 2, 2, 1}

Therefore, the minimum number of elements required is 2.

Naive Approach:

The simplest approach to solve the problem is to generate all the possible subarrays from the given array of size less than equal to N/2 and, for each subarray, check if performing mirror operation gives the array arr[] or not. Print the minimum length subarray satisfying the condition. If no subarray is found to be satisfying, print No.

Time Complexity:_ O(N3)_

Auxiliary Space:_ O(N)_

Efficient Approach:

The above approach can be further optimized using Divide and Conquer technique. Follow the steps below to solve the problem:

  • Initialize a variable K = N and then, check whether the prefix of A[] of length K is a palindrome or not.
  • If the prefix of length **K **is a palindrome then divide K by 2 and perform the above checking.
  • If the prefix is not a palindrome then the answer is the current value of K.
  • Keep checking while K > 0 until K is odd.
  • If K is odd, then print the current value of K.

Below is the implementation of the above approach:

  • C++

// C++ Program to implement

// the above approach

#include <bits/stdc++.h>

**using** **namespace** std;

// Function to find minimum number

// of elements required to form A[]

// by performing mirroring operation

**int** minimumrequired(``**int** A[], **int** N)

{

// Initialize K

**int** K = N;

**int** ans;

**while** (K > 0) {

// Odd length array

// cannot be formed by

// mirror operation

**if** (K % 2 == 1) {

ans = K;

**break**``;

}

**bool** ispalindrome = 1;

// Check if prefix of

// length K is palindrome

**for** (``**int** i = 0; i < K / 2; i++) {

// Check if not a palindrome

**if** (A[i] != A[K - 1 - i])

ispalindrome = 0;

}

// If found to be palindrome

**if** (ispalindrome) {

ans = K / 2;

K /= 2;

}

// Otherwise

**else** {

ans = K;

**break**``;

}

}

// Return the final answer

**return** ans;

}

// Driver Code

**int** main()

{

**int** a[] = { 1, 2, 2, 1, 1, 2, 2, 1 };

**int** N = **sizeof** a / **sizeof** a[0];

cout << minimumrequired(a, N);

**return** 0;

}

Output:

2

Time Complexity:_ O(N*log N)_

_Auxiliary Space: _O(N)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

#arrays #divide and conquer #greedy #array-rearrange #palindrome #prefix

Houston  Sipes

Houston Sipes

1598029200

Maximize Sum possible from an Array by the given moves

Given three integers N, M and K and an array a[] consisting of N integers, where M and K denotes the total number of possible moves and the number of possible moves(shift by an index) on the left of the current element in an array respectively, the task is to maximize the sum possible by traversing the array utilizing all the available moves.

Examples:

_Input: _N = 5, M = 4, K = 0, a[] = {1, 5, 4, 3, 2}

Output:_ 15_

Explanation:

Since no moves towards left is possible, therefore, the only possible path is a[0] -> a[1] -> a[2] -> a[3] -> a[4].

Therefore, the sum calculated is 15.

_Input: _N = 5, M = 4, K = 1, a[]= {1, 5, 4, 3, 2}

Output:_ 19_

Explanation:

The maximum sum can be obtained in the path a[0] -> a[1] -> a[2] -> a[1] -> a[2]

Therefore, the maximum possible sum = 19

**Approach: **The above problem can be solved using Dynamic Programming. Follow the steps below to solve the problem:

  • Initialize a dp[][] matrix such that dp[i][j] stores the maximum sum possible up to ith index by using j left moves.
  • It can be observed that left move is possible only if** i ≥ 1** and** k > 0** and a right move is possible if i < n – 1.
  • Check the conditions and update the maximum of the sums possible from the above two moves and store in dp[i][j].

Below is the implementation of the above approach:

  • Java

filter_none

edit

play_arrow

brightness_4

// Java Program to implement

// the above approach

**import** java.io.*;

**import** java.util.*;

**public** **class** GFG {

// Function to find the maximum sum possible

// by given moves from the array

**public** **static** **int** maxValue(``**int** a[], **int** n, **int** pos,

**int** moves, **int** left,

**int** dp[][])

{

// Checking for boundary

**if** (moves == 0 || (pos > n - 1 || pos < 0``))

**return** 0``;

// If previously computed subproblem occurs

**if** (dp[pos][left] != -``1``)

**return** dp[pos][left];

**int** value = 0``;

// If element can be moved left

**if** (left > 0 && pos >= 1``)

// Calculate maximum possible sum

// by moving left from current index

value = Math.max(

value, a[pos] + maxValue(a, n, pos - 1``,

moves - 1``, left - 1``, dp));

// If element can be moved right

**if** (pos <= n - 1``)

// Calculate maximum possible sum

// by moving right from current index

// and update the maximum sum

value = Math.max(

value, a[pos]

+ maxValue(a, n, pos + 1``,

moves - 1``, left, dp));

// Store the maximum sum

**return** dp[pos][left] = value;

}

// Driver Code

**public** **static** **void** main(String args[])

{

**int** n = 5``;

**int** a[] = { 1``, 5``, 4``, 3``, 2 };

**int** k = 1``;

**int** m = 4``;

**int** dp[][] = **new** **int**``[n + 1``][k + 1``];

**for** (``**int** i[] : dp)

Arrays.fill(i, -``1``);

System.out.println(

(a[``0``] + maxValue(a, n, 1``, m, k, dp)));

}

}

Output:

19

_Time Complexity: _O(N * K)

_Auxiliary Space: _O(N * K)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

#arrays #dynamic programming #mathematical #recursion #array-traversal-question