|
| 1 | +/* |
| 2 | +Get Maximum in Generated Array |
| 3 | +=============================== |
| 4 | +
|
| 5 | +You are given an integer n. An array nums of length n + 1 is generated in the following way: |
| 6 | +
|
| 7 | +nums[0] = 0 |
| 8 | +nums[1] = 1 |
| 9 | +nums[2 * i] = nums[i] when 2 <= 2 * i <= n |
| 10 | +nums[2 * i + 1] = nums[i] + nums[i + 1] when 2 <= 2 * i + 1 <= n |
| 11 | +Return the maximum integer in the array nums. |
| 12 | +
|
| 13 | +Example 1: |
| 14 | +Input: n = 7 |
| 15 | +Output: 3 |
| 16 | +Explanation: According to the given rules: |
| 17 | + nums[0] = 0 |
| 18 | + nums[1] = 1 |
| 19 | + nums[(1 * 2) = 2] = nums[1] = 1 |
| 20 | + nums[(1 * 2) + 1 = 3] = nums[1] + nums[2] = 1 + 1 = 2 |
| 21 | + nums[(2 * 2) = 4] = nums[2] = 1 |
| 22 | + nums[(2 * 2) + 1 = 5] = nums[2] + nums[3] = 1 + 2 = 3 |
| 23 | + nums[(3 * 2) = 6] = nums[3] = 2 |
| 24 | + nums[(3 * 2) + 1 = 7] = nums[3] + nums[4] = 2 + 1 = 3 |
| 25 | +Hence, nums = [0,1,1,2,1,3,2,3], and the maximum is 3. |
| 26 | +
|
| 27 | +Example 2: |
| 28 | +Input: n = 2 |
| 29 | +Output: 1 |
| 30 | +Explanation: According to the given rules, the maximum between nums[0], nums[1], and nums[2] is 1. |
| 31 | +
|
| 32 | +Example 3: |
| 33 | +Input: n = 3 |
| 34 | +Output: 2 |
| 35 | +Explanation: According to the given rules, the maximum between nums[0], nums[1], nums[2], and nums[3] is 2. |
| 36 | +
|
| 37 | +Constraints: |
| 38 | +0 <= n <= 100 |
| 39 | +
|
| 40 | +Hint #1 |
| 41 | +Try generating the array. |
| 42 | +
|
| 43 | +Hint #2 |
| 44 | +Make sure not to fall in the base case of 0. |
| 45 | +*/ |
| 46 | + |
| 47 | +class Solution |
| 48 | +{ |
| 49 | +public: |
| 50 | + int getMaximumGenerated(int n) |
| 51 | + { |
| 52 | + n++; |
| 53 | + if (n <= 2) |
| 54 | + return n - 1; |
| 55 | + vector<int> arr(n, -1); |
| 56 | + arr[0] = 0; |
| 57 | + arr[1] = 1; |
| 58 | + int ans = INT_MIN; |
| 59 | + |
| 60 | + for (int i = 2; i < n; ++i) |
| 61 | + { |
| 62 | + if (i % 2 == 0) |
| 63 | + { |
| 64 | + arr[i] = arr[i / 2]; |
| 65 | + } |
| 66 | + else |
| 67 | + arr[i] = arr[(i - 1) / 2] + arr[(i + 1) / 2]; |
| 68 | + ans = max(ans, arr[i]); |
| 69 | + } |
| 70 | + |
| 71 | + return ans; |
| 72 | + } |
| 73 | +}; |
0 commit comments