Skip to content

Commit

Permalink
leetcode: 1646. Get Maximum in Generated Array -- Array | Easy
Browse files Browse the repository at this point in the history
  • Loading branch information
ympons committed Jan 16, 2021
1 parent 4173e24 commit 4b9b958
Show file tree
Hide file tree
Showing 3 changed files with 96 additions and 0 deletions.
29 changes: 29 additions & 0 deletions leetcode/1646-get-maximum-in-generated-array/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
# 1646. Get Maximum in Generated Array

You are given an integer `n`. An array `nums` of length `n + 1` is generated in the following way:

- nums[0] = 0
- nums[1] = 1
- nums[2 * i] = nums[i] when 2 <= 2 * i <= n
- nums[2 * i + 1] = nums[i] + nums[i + 1] when 2 <= 2 * i + 1 <= n

*Return the **maximum** integer in the array `nums`.*

**Example:**
```
Input: n = 7
Output: 3
Explanation: According to the given rules:
nums[0] = 0
nums[1] = 1
nums[(1 * 2) = 2] = nums[1] = 1
nums[(1 * 2) + 1 = 3] = nums[1] + nums[2] = 1 + 1 = 2
nums[(2 * 2) = 4] = nums[2] = 1
nums[(2 * 2) + 1 = 5] = nums[2] + nums[3] = 1 + 2 = 3
nums[(3 * 2) = 6] = nums[3] = 2
nums[(3 * 2) + 1 = 7] = nums[3] + nums[4] = 2 + 1 = 3
Hence, nums = [0,1,1,2,1,3,2,3], and the maximum is 3.
```

**Constraints:**
- `0 <= n <= 1000`
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package leetcode

func getMaximumGenerated(n int) int {
if n < 2 {
return n
}
nums, max := make([]int, n+1), 0
nums[1] = 1
for i := 1; i <= n/2; i++ {
nums[2*i] = nums[i]
if max < nums[i] {
max = nums[i]
}
if 2*i+1 > n {
return max
}
nums[2*i+1] = nums[i] + nums[i+1]
if max < nums[2*i+1] {
max = nums[2*i+1]
}
}
return max
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
package leetcode

import (
"testing"

"github.com/stretchr/testify/assert"
)

func TestGetMaximumGenerated(t *testing.T) {
assert := assert.New(t)
for _, test := range tests {
assert.Equal(test.expected, getMaximumGenerated(test.input))
}
}

var tests = []struct {
input int
expected int
}{
{
input: 6,
expected: 3,
},
{
input: 100,
expected: 21,
},
{
input: 0,
expected: 0,
},
{
input: 1,
expected: 1,
},
{
input: 7,
expected: 3,
},
{
input: 1000,
expected: 89,
},
}

0 comments on commit 4b9b958

Please sign in to comment.