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++
|
Time Complexity: O(1)
Auxiliary Area: O(1)