Skip to content

Commit f0a155e

Browse files
authored
Merge pull request TheAlgorithms#160 from jsca-kwok/jk-max-69-number
Add solution for max 69 number algorithm
2 parents 1eefa23 + 47efd01 commit f0a155e

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-0
lines changed

DIRECTORY.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@
2727
* [Get Products Of All Other Elements](https://github.com/TheAlgorithms/Ruby/blob/master/data_structures/arrays/get_products_of_all_other_elements.rb)
2828
* [Good Pairs](https://github.com/TheAlgorithms/Ruby/blob/master/data_structures/arrays/good_pairs.rb)
2929
* [Intersection](https://github.com/TheAlgorithms/Ruby/blob/master/data_structures/arrays/intersection.rb)
30+
* [Max 69 Number](https://github.com/TheAlgorithms/Ruby/blob/master/data_structures/arrays/max_69_number.rb)
3031
* [Next Greater Element](https://github.com/TheAlgorithms/Ruby/blob/master/data_structures/arrays/next_greater_element.rb)
3132
* [Remove Elements](https://github.com/TheAlgorithms/Ruby/blob/master/data_structures/arrays/remove_elements.rb)
3233
* [Richest Customer Wealth](https://github.com/TheAlgorithms/Ruby/blob/master/data_structures/arrays/richest_customer_wealth.rb)
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
# Challenge name: Maximum 69 number
2+
#
3+
# Given a positive integer num consisting only of digits 6 and 9.
4+
# Return the maximum number you can get by changing at most one digit (6 becomes 9, and 9 becomes 6).
5+
#
6+
# Example 1:
7+
# Input: num = 9669
8+
# Output: 9969
9+
# Explanation:
10+
# Changing the first digit results in 6669.
11+
# Changing the second digit results in 9969.
12+
# Changing the third digit results in 9699.
13+
# Changing the fourth digit results in 9666.
14+
# The maximum number is 9969.
15+
#
16+
# Example 2:
17+
# Input: num = 9996
18+
# Output: 9999
19+
# Explanation: Changing the last digit 6 to 9 results in the maximum number.
20+
21+
#
22+
# Approach 1: Logical Approach
23+
# Explanation: Changing the first available 6 to a 9 will give the max number
24+
#
25+
def max_number(num)
26+
arr = num.to_s.split('')
27+
28+
arr.each_with_index do |num, i|
29+
if num == '6'
30+
arr[i] = '9'
31+
return arr.join.to_i
32+
end
33+
end
34+
end
35+
36+
puts max_number(9669)
37+
# => 9969
38+
39+
puts max_number(9996)
40+
# => 9999

0 commit comments

Comments
 (0)