8.2 C
New York
Sunday, November 17, 2024

Maximize worth obtained in Array by leaping to the subsequent consecutive higher

Share To Your Friends

[ad_1]

Given an array arr[] of dimension N, the duty is to seek out the utmost worth that may be obtained by following the beneath circumstances:

  • Choose any factor (say okay) from the array and enhance all different components by 1.
  • Within the subsequent step, soar solely to the index with a price okay+1.
  • Ultimately, you’re on the most worth.

Examples:

Enter: N = 4, arr[] ={1, 2, 1, 3}
Output: 3
Clarification: If began from index 0 with a peak of 1 unit, then,  
the brand new worth of array might be [1, 3, 2, 4]. 
Then soar to the index with (1+1 = 2) ie 2nd index,  
The up to date values are [2, 4, 2, 5]. Can’t be on the most worth at finish
The primary chosen worth was 3 at index 3. 
The up to date values are [2, 3, 2, 3]. Max achieved -3. Therefore ans = 3;

Enter: N = 4, arr[]={1, 2, 3, 3}
Output: 4

 

Strategy: The issue may be solved primarily based on the next commentary:

On commentary, we are able to understand that for reaching most peak we’ve two choices

  • Immediately choosing the utmost heighted podium initially accessible.
  • Selecting all the weather (say whole y) with similar worth (say x). So highest quantity that may be reached is (x + y – 1).

Comply with the beneath steps to resolve the issue:

  • Type the array in growing order.
  • Search for the span of the identical worth components and get the utmost worth that may be achieved from that span utilizing the above thought.
  • Carry out this for all accessible spans and retailer the utmost.
  • Return the most because the required reply.

Beneath is the implementation of the above method.

C++

  

#embrace <bits/stdc++.h>

utilizing namespace std;

  

int maxVal(int n, int a[])

{

    

    

    type(a, a + n);

    int ans = 0, span = 0;

    for (int i = 1; i < n; i++) {

  

        

        if (a[i - 1] == a[i]) {

            span++;

        }

        else {

  

            

            

            ans = max(ans, a[i - 1] + span);

            span = 0;

        }

    }

    ans = max(ans, a[n - 1] + span);

    ans = max(ans, a[n - 1]);

  

    

    

    return ans;

}

  

int most important()

{

    int N = 4;

    int arr[] = { 1, 2, 1, 3 };

  

    

    cout << maxVal(N, arr) << endl;

    return 0;

}

Time Complexity: O(N*logN)
Auxiliary Area: O(1)

[ad_2]


Share To Your Friends

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles