Monday, September 19, 2022
HomeWordPress DevelopmentMaximize the cash when no two adjoining Array indices might be chosen

Maximize the cash when no two adjoining Array indices might be chosen


View Dialogue

Enhance Article

Save Article

Like Article

View Dialogue

Enhance Article

Save Article

Like Article

Given an array of dimension N, every index has Okay sum of money, the goal is to choose the utmost sum of money from the array however the constraint is that no two adjoining indices might be chosen.

Examples:

Enter: N = 5, Okay = 10
Output: 30
Clarification: The doable choice is to choose from the primary,  
third and fifth homes which can lead to 30.

Enter: N = 2, Okay = 12
Output: 12
Clarification: The one decisions are to choose 
from the primary or second which can lead to 12.

Method: The issue might be solved utilizing the next statement:

There might be two instances:

  • Case 1 (N is odd): You possibly can both select 1, 3, 5, . . . or 2, 4, 6, . . . In first case all the time depend is yet another than the second so, you select first. Complete indices that may be chosen = (N+1)/2
  • Case 2 (N is even): You possibly can both select 1, 3, . . . or 2, 4, . . . In each case all the time depend of components is equal so you may select any. Complete indices chosen = N/2

Observe the steps to resolve this downside:

  • Test the parity of N:
    • If N is odd, return (N+1)*Okay / 2
    • Else, return N*Okay  / 2

Under is the implementation of the above method.

C++

  

#embody <bits/stdc++.h>

utilizing namespace std;

  

int maximizeMoney(int N, int Okay)

{

    if (N & 1)

        return (N + 1) * Okay / 2;

    else

        return N * Okay / 2;

}

  

int principal()

{

    int N = 5, Okay = 10;

  

    

    cout << maximizeMoney(N, Okay) << endl;

    return 0;

}

Time Complexity: O(1)
Auxiliary Area: O(1)

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments