Skip to content

Commit 0717a30

Browse files
authored
Added tasks 2001-2400
1 parent 4a4a339 commit 0717a30

File tree

292 files changed

+26694
-147
lines changed
  • src/main/kotlin
    • g1901_2000/s1978_employees_whose_manager_left_the_company
    • g2001_2100
      • s2001_number_of_pairs_of_interchangeable_rectangles
      • s2002_maximum_product_of_the_length_of_two_palindromic_subsequences
      • s2003_smallest_missing_genetic_value_in_each_subtree
      • s2006_count_number_of_pairs_with_absolute_difference_k
      • s2007_find_original_array_from_doubled_array
      • s2008_maximum_earnings_from_taxi
      • s2009_minimum_number_of_operations_to_make_array_continuous
      • s2053_kth_distinct_string_in_an_array
      • s2054_two_best_non_overlapping_events
      • s2055_plates_between_candles
      • s2056_number_of_valid_move_combinations_on_chessboard
      • s2057_smallest_index_with_equal_value
      • s2058_find_the_minimum_and_maximum_number_of_nodes_between_critical_points
      • s2059_minimum_operations_to_convert_number
      • s2060_check_if_an_original_string_exists_given_two_encoded_strings
      • s2062_count_vowel_substrings_of_a_string
      • s2063_vowels_of_all_substrings
      • s2064_minimized_maximum_of_products_distributed_to_any_store
      • s2065_maximum_path_quality_of_a_graph
      • s2068_check_whether_two_strings_are_almost_equivalent
      • s2069_walking_robot_simulation_ii
      • s2070_most_beautiful_item_for_each_query
      • s2071_maximum_number_of_tasks_you_can_assign
      • s2073_time_needed_to_buy_tickets
      • s2074_reverse_nodes_in_even_length_groups
      • s2075_decode_the_slanted_ciphertext
      • s2076_process_restricted_friend_requests
      • s2078_two_furthest_houses_with_different_colors
      • s2079_watering_plants
      • s2080_range_frequency_queries
      • s2081_sum_of_k_mirror_numbers
      • s2085_count_common_words_with_one_occurrence
      • s2086_minimum_number_of_food_buckets_to_feed_the_hamsters
      • s2087_minimum_cost_homecoming_of_a_robot_in_a_grid
      • s2088_count_fertile_pyramids_in_a_land
      • s2089_find_target_indices_after_sorting_array
      • s2090_k_radius_subarray_averages
      • s2091_removing_minimum_and_maximum_from_array
      • s2092_find_all_people_with_secret
      • s2094_finding_3_digit_even_numbers
      • s2095_delete_the_middle_node_of_a_linked_list
      • s2096_step_by_step_directions_from_a_binary_tree_node_to_another
      • s2097_valid_arrangement_of_pairs
      • s2099_find_subsequence_of_length_k_with_the_largest_sum
      • s2100_find_good_days_to_rob_the_bank
    • g2101_2200
      • s2101_detonate_the_maximum_bombs
      • s2102_sequentially_ordinal_rank_tracker
      • s2103_rings_and_rods
      • s2104_sum_of_subarray_ranges
      • s2105_watering_plants_ii
      • s2106_maximum_fruits_harvested_after_at_most_k_steps
      • s2108_find_first_palindromic_string_in_the_array
      • s2109_adding_spaces_to_a_string
      • s2110_number_of_smooth_descent_periods_of_a_stock
      • s2111_minimum_operations_to_make_the_array_k_increasing
      • s2114_maximum_number_of_words_found_in_sentences
      • s2115_find_all_possible_recipes_from_given_supplies
      • s2116_check_if_a_parentheses_string_can_be_valid
      • s2117_abbreviating_the_product_of_a_range
      • s2119_a_number_after_a_double_reversal
      • s2120_execution_of_all_suffix_instructions_staying_in_a_grid
      • s2121_intervals_between_identical_elements
      • s2122_recover_the_original_array
      • s2124_check_if_all_as_appears_before_all_bs
      • s2125_number_of_laser_beams_in_a_bank
      • s2126_destroying_asteroids
      • s2127_maximum_employees_to_be_invited_to_a_meeting
      • s2129_capitalize_the_title
      • s2130_maximum_twin_sum_of_a_linked_list
      • s2131_longest_palindrome_by_concatenating_two_letter_words
      • s2132_stamping_the_grid
      • s2133_check_if_every_row_and_column_contains_all_numbers
      • s2134_minimum_swaps_to_group_all_1s_together_ii
      • s2135_count_words_obtained_after_adding_a_letter
      • s2136_earliest_possible_day_of_full_bloom
      • s2138_divide_a_string_into_groups_of_size_k
      • s2139_minimum_moves_to_reach_target_score
      • s2140_solving_questions_with_brainpower
      • s2141_maximum_running_time_of_n_computers
      • s2144_minimum_cost_of_buying_candies_with_discount
      • s2145_count_the_hidden_sequences
      • s2146_k_highest_ranked_items_within_a_price_range
      • s2147_number_of_ways_to_divide_a_long_corridor
      • s2148_count_elements_with_strictly_smaller_and_greater_elements
      • s2149_rearrange_array_elements_by_sign
      • s2150_find_all_lonely_numbers_in_the_array
      • s2151_maximum_good_people_based_on_statements
      • s2154_keep_multiplying_found_values_by_two
      • s2155_all_divisions_with_the_highest_score_of_a_binary_array
      • s2156_find_substring_with_given_hash_value
      • s2157_groups_of_strings
      • s2160_minimum_sum_of_four_digit_number_after_splitting_digits
      • s2161_partition_array_according_to_given_pivot
      • s2162_minimum_cost_to_set_cooking_time
      • s2163_minimum_difference_in_sums_after_removal_of_elements
      • s2164_sort_even_and_odd_indices_independently
      • s2165_smallest_value_of_the_rearranged_number
      • s2166_design_bitset
      • s2167_minimum_time_to_remove_all_cars_containing_illegal_goods
      • s2169_count_operations_to_obtain_zero
      • s2170_minimum_operations_to_make_the_array_alternating
      • s2171_removing_minimum_number_of_magic_beans
      • s2172_maximum_and_sum_of_array
      • s2176_count_equal_and_divisible_pairs_in_an_array
      • s2177_find_three_consecutive_integers_that_sum_to_a_given_number
      • s2178_maximum_split_of_positive_even_integers
      • s2179_count_good_triplets_in_an_array
      • s2180_count_integers_with_even_digit_sum
      • s2181_merge_nodes_in_between_zeros
      • s2182_construct_string_with_repeat_limit
      • s2183_count_array_pairs_divisible_by_k
      • s2185_counting_words_with_a_given_prefix
      • s2186_minimum_number_of_steps_to_make_two_strings_anagram_ii
      • s2187_minimum_time_to_complete_trips
      • s2188_minimum_time_to_finish_the_race
      • s2190_most_frequent_number_following_key_in_an_array
      • s2191_sort_the_jumbled_numbers
      • s2192_all_ancestors_of_a_node_in_a_directed_acyclic_graph
      • s2193_minimum_number_of_moves_to_make_palindrome
      • s2194_cells_in_a_range_on_an_excel_sheet
      • s2195_append_k_integers_with_minimal_sum
      • s2196_create_binary_tree_from_descriptions
      • s2197_replace_non_coprime_numbers_in_array
      • s2200_find_all_k_distant_indices_in_an_array
    • g2201_2300
      • s2201_count_artifacts_that_can_be_extracted
      • s2202_maximize_the_topmost_element_after_k_moves
      • s2203_minimum_weighted_subgraph_with_the_required_paths
      • s2206_divide_array_into_equal_pairs
      • s2207_maximize_number_of_subsequences_in_a_string
      • s2208_minimum_operations_to_halve_array_sum
      • s2209_minimum_white_tiles_after_covering_with_carpets
      • s2210_count_hills_and_valleys_in_an_array
      • s2211_count_collisions_on_a_road
      • s2212_maximum_points_in_an_archery_competition
      • s2213_longest_substring_of_one_repeating_character
      • s2215_find_the_difference_of_two_arrays
      • s2216_minimum_deletions_to_make_array_beautiful
      • s2217_find_palindrome_with_fixed_length
      • s2218_maximum_value_of_k_coins_from_piles
      • s2220_minimum_bit_flips_to_convert_number
      • s2221_find_triangular_sum_of_an_array
      • s2222_number_of_ways_to_select_buildings
      • s2223_sum_of_scores_of_built_strings
      • s2224_minimum_number_of_operations_to_convert_time
      • s2225_find_players_with_zero_or_one_losses
      • s2226_maximum_candies_allocated_to_k_children
      • s2227_encrypt_and_decrypt_strings
      • s2231_largest_number_after_digit_swaps_by_parity
      • s2232_minimize_result_by_adding_parentheses_to_expression
      • s2233_maximum_product_after_k_increments
      • s2234_maximum_total_beauty_of_the_gardens
      • s2235_add_two_integers
      • s2236_root_equals_sum_of_children
      • s2239_find_closest_number_to_zero
      • s2240_number_of_ways_to_buy_pens_and_pencils
      • s2241_design_an_atm_machine
      • s2242_maximum_score_of_a_node_sequence
      • s2243_calculate_digit_sum_of_a_string
      • s2244_minimum_rounds_to_complete_all_tasks
      • s2245_maximum_trailing_zeros_in_a_cornered_path
      • s2246_longest_path_with_different_adjacent_characters
      • s2248_intersection_of_multiple_arrays
      • s2249_count_lattice_points_inside_a_circle
      • s2250_count_number_of_rectangles_containing_each_point
      • s2251_number_of_flowers_in_full_bloom
      • s2255_count_prefixes_of_a_given_string
      • s2256_minimum_average_difference
      • s2257_count_unguarded_cells_in_the_grid
      • s2258_escape_the_spreading_fire
      • s2259_remove_digit_from_number_to_maximize_result
      • s2260_minimum_consecutive_cards_to_pick_up
      • s2261_k_divisible_elements_subarrays
      • s2262_total_appeal_of_a_string
      • s2264_largest_3_same_digit_number_in_string
      • s2265_count_nodes_equal_to_average_of_subtree
      • s2266_count_number_of_texts
      • s2267_check_if_there_is_a_valid_parentheses_string_path
      • s2269_find_the_k_beauty_of_a_number
      • s2270_number_of_ways_to_split_array
      • s2271_maximum_white_tiles_covered_by_a_carpet
      • s2272_substring_with_largest_variance
      • s2273_find_resultant_array_after_removing_anagrams
      • s2274_maximum_consecutive_floors_without_special_floors
      • s2275_largest_combination_with_bitwise_and_greater_than_zero
      • s2276_count_integers_in_intervals
      • s2278_percentage_of_letter_in_string
      • s2279_maximum_bags_with_full_capacity_of_rocks
      • s2280_minimum_lines_to_represent_a_line_chart
      • s2281_sum_of_total_strength_of_wizards
      • s2283_check_if_number_has_equal_digit_count_and_digit_value
      • s2284_sender_with_largest_word_count
      • s2285_maximum_total_importance_of_roads
      • s2286_booking_concert_tickets_in_groups
      • s2287_rearrange_characters_to_make_target_string
      • s2288_apply_discount_to_prices
      • s2289_steps_to_make_array_non_decreasing
      • s2290_minimum_obstacle_removal_to_reach_corner
      • s2293_min_max_game
      • s2294_partition_array_such_that_maximum_difference_is_k
      • s2295_replace_elements_in_an_array
      • s2296_design_a_text_editor
      • s2299_strong_password_checker_ii
      • s2300_successful_pairs_of_spells_and_potions
    • g2301_2400
      • s2301_match_substring_after_replacement
      • s2302_count_subarrays_with_score_less_than_k
      • s2303_calculate_amount_paid_in_taxes
      • s2304_minimum_path_cost_in_a_grid
      • s2305_fair_distribution_of_cookies
      • s2306_naming_a_company
      • s2309_greatest_english_letter_in_upper_and_lower_case
      • s2310_sum_of_numbers_with_units_digit_k
      • s2311_longest_binary_subsequence_less_than_or_equal_to_k
      • s2312_selling_pieces_of_wood
      • s2315_count_asterisks
      • s2316_count_unreachable_pairs_of_nodes_in_an_undirected_graph
      • s2317_maximum_xor_after_operations
      • s2318_number_of_distinct_roll_sequences
      • s2319_check_if_matrix_is_x_matrix
      • s2320_count_number_of_ways_to_place_houses
      • s2321_maximum_score_of_spliced_array
      • s2322_minimum_score_after_removals_on_a_tree
      • s2325_decode_the_message
      • s2326_spiral_matrix_iv
      • s2327_number_of_people_aware_of_a_secret
      • s2328_number_of_increasing_paths_in_a_grid
      • s2331_evaluate_boolean_binary_tree
      • s2332_the_latest_time_to_catch_a_bus
      • s2333_minimum_sum_of_squared_difference
      • s2334_subarray_with_elements_greater_than_varying_threshold
      • s2335_minimum_amount_of_time_to_fill_cups
      • s2336_smallest_number_in_infinite_set
      • s2337_move_pieces_to_obtain_a_string
      • s2338_count_the_number_of_ideal_arrays
      • s2341_maximum_number_of_pairs_in_array
      • s2342_max_sum_of_a_pair_with_equal_sum_of_digits
      • s2343_query_kth_smallest_trimmed_number
      • s2344_minimum_deletions_to_make_array_divisible
      • s2347_best_poker_hand
      • s2348_number_of_zero_filled_subarrays
      • s2349_design_a_number_container_system
      • s2350_shortest_impossible_sequence_of_rolls
      • s2351_first_letter_to_appear_twice
      • s2352_equal_row_and_column_pairs
      • s2353_design_a_food_rating_system
      • s2354_number_of_excellent_pairs
      • s2356_number_of_unique_subjects_taught_by_each_teacher
      • s2357_make_array_zero_by_subtracting_equal_amounts
      • s2358_maximum_number_of_groups_entering_a_competition
      • s2359_find_closest_node_to_given_two_nodes
      • s2360_longest_cycle_in_a_graph
      • s2363_merge_similar_items
      • s2364_count_number_of_bad_pairs
      • s2365_task_scheduler_ii
      • s2366_minimum_replacements_to_sort_the_array
      • s2367_number_of_arithmetic_triplets
      • s2368_reachable_nodes_with_restrictions
      • s2369_check_if_there_is_a_valid_partition_for_the_array
      • s2370_longest_ideal_subsequence
      • s2373_largest_local_values_in_a_matrix
      • s2374_node_with_highest_edge_score
      • s2375_construct_smallest_number_from_di_string
      • s2376_count_special_integers
      • s2379_minimum_recolors_to_get_k_consecutive_black_blocks
      • s2380_time_needed_to_rearrange_a_binary_string
      • s2381_shifting_letters_ii
      • s2382_maximum_segment_sum_after_removals
      • s2383_minimum_hours_of_training_to_win_a_competition
      • s2384_largest_palindromic_number
      • s2385_amount_of_time_for_binary_tree_to_be_infected
      • s2386_find_the_k_sum_of_an_array
      • s2389_longest_subsequence_with_limited_sum
      • s2390_removing_stars_from_a_string
      • s2391_minimum_amount_of_time_to_collect_garbage
      • s2392_build_a_matrix_with_conditions
      • s2395_find_subarrays_with_equal_sum
      • s2396_strictly_palindromic_number
      • s2397_maximum_rows_covered_by_columns
      • s2398_maximum_number_of_robots_within_budget
      • s2399_check_distances_between_same_letters
      • s2400_number_of_ways_to_reach_a_position_after_exactly_k_steps
    • g2401_2500
      • s2401_longest_nice_subarray
      • s2402_meeting_rooms_iii
      • s2404_most_frequent_even_element
      • s2405_optimal_partition_of_string
      • s2406_divide_intervals_into_minimum_number_of_groups
      • s2407_longest_increasing_subsequence_ii
      • s2409_count_days_spent_together
      • s2410_maximum_matching_of_players_with_trainers
      • s2411_smallest_subarrays_with_maximum_bitwise_or
      • s2412_minimum_money_required_before_transactions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

292 files changed

+26694
-147
lines changed

README.md

Lines changed: 439 additions & 147 deletions
Large diffs are not rendered by default.
Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin)
2+
[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork)
3+
4+
## 1978\. Employees Whose Manager Left the Company
5+
6+
Easy
7+
8+
SQL Schema
9+
10+
Table: `Employees`
11+
12+
+-------------+----------+
13+
| Column Name | Type |
14+
+-------------+----------+
15+
| employee_id | int |
16+
| name | varchar |
17+
| manager_id | int |
18+
| salary | int |
19+
+-------------+----------+
20+
21+
employee_id is the primary key for this table. This table contains information about the employees, their salary, and the ID of their manager. Some employees do not have a manager (manager_id is null).
22+
23+
Write an SQL query to report the IDs of the employees whose salary is strictly less than `$30000` and whose manager left the company. When a manager leaves the company, their information is deleted from the `Employees` table, but the reports still have their `manager_id` set to the manager that left.
24+
25+
Return the result table ordered by `employee_id`.
26+
27+
The query result format is in the following example.
28+
29+
**Example 1:**
30+
31+
**Input: ** Employees table:
32+
33+
+-------------+-----------+------------+--------+
34+
| employee_id | name | manager_id | salary |
35+
+-------------+-----------+------------+--------+
36+
| 3 | Mila | 9 | 60301 |
37+
| 12 | Antonella | null | 31000 |
38+
| 13 | Emery | null | 67084 |
39+
| 1 | Kalel | 11 | 21241 |
40+
| 9 | Mikaela | null | 50937 |
41+
| 11 | Joziah | 6 | 28485 |
42+
+-------------+-----------+------------+--------+
43+
44+
**Output:**
45+
46+
+-------------+
47+
| employee_id |
48+
+-------------+
49+
| 11 |
50+
+-------------+
51+
52+
**Explanation:**
53+
54+
The employees with a salary less than $30000 are 1 (Kalel) and 11 (Joziah).
55+
56+
Kalel's manager is employee 11, who is still in the company (Joziah).
57+
58+
Joziah's manager is employee 6, who left the company because there is no row for employee 6 as it was deleted.
59+
60+
## Solution
61+
62+
```sql
63+
# Write your MySQL query statement below
64+
select employee_id from employees where manager_id not in (select distinct (employee_id) from employees)
65+
AND salary < 30000 order by employee_id
66+
```
Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin)
2+
[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork)
3+
4+
## 2001\. Number of Pairs of Interchangeable Rectangles
5+
6+
Medium
7+
8+
You are given `n` rectangles represented by a **0-indexed** 2D integer array `rectangles`, where <code>rectangles[i] = [width<sub>i</sub>, height<sub>i</sub>]</code> denotes the width and height of the <code>i<sup>th</sup></code> rectangle.
9+
10+
Two rectangles `i` and `j` (`i < j`) are considered **interchangeable** if they have the **same** width-to-height ratio. More formally, two rectangles are **interchangeable** if <code>width<sub>i</sub>/height<sub>i</sub> == width<sub>j</sub>/height<sub>j</sub></code> (using decimal division, not integer division).
11+
12+
Return _the **number** of pairs of **interchangeable** rectangles in_ `rectangles`.
13+
14+
**Example 1:**
15+
16+
**Input:** rectangles = \[\[4,8],[3,6],[10,20],[15,30]]
17+
18+
**Output:** 6
19+
20+
**Explanation:** The following are the interchangeable pairs of rectangles by index (0-indexed):
21+
22+
- Rectangle 0 with rectangle 1: 4/8 == 3/6.
23+
24+
- Rectangle 0 with rectangle 2: 4/8 == 10/20.
25+
26+
- Rectangle 0 with rectangle 3: 4/8 == 15/30.
27+
28+
- Rectangle 1 with rectangle 2: 3/6 == 10/20.
29+
30+
- Rectangle 1 with rectangle 3: 3/6 == 15/30.
31+
32+
- Rectangle 2 with rectangle 3: 10/20 == 15/30.
33+
34+
**Example 2:**
35+
36+
**Input:** rectangles = \[\[4,5],[7,8]]
37+
38+
**Output:** 0
39+
40+
**Explanation:** There are no interchangeable pairs of rectangles.
41+
42+
**Constraints:**
43+
44+
* `n == rectangles.length`
45+
* <code>1 <= n <= 10<sup>5</sup></code>
46+
* `rectangles[i].length == 2`
47+
* <code>1 <= width<sub>i</sub>, height<sub>i</sub> <= 10<sup>5</sup></code>
48+
49+
## Solution
50+
51+
```kotlin
52+
@Suppress("NAME_SHADOWING")
53+
class Solution {
54+
private fun factorial(n: Long): Long {
55+
var n = n
56+
var m: Long = 0
57+
while (n > 0) {
58+
m += n
59+
n -= 1
60+
}
61+
return m
62+
}
63+
64+
fun interchangeableRectangles(rec: Array<IntArray>): Long {
65+
val ratio = DoubleArray(rec.size)
66+
for (i in rec.indices) {
67+
ratio[i] = rec[i][0].toDouble() / rec[i][1]
68+
}
69+
ratio.sort()
70+
var res: Long = 0
71+
var k = 0
72+
for (j in 0 until ratio.size - 1) {
73+
if (ratio[j] == ratio[j + 1]) {
74+
k++
75+
}
76+
if (ratio[j] != ratio[j + 1] || j + 2 == ratio.size) {
77+
res += factorial(k.toLong())
78+
k = 0
79+
}
80+
}
81+
return res
82+
}
83+
}
84+
```
Lines changed: 122 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,122 @@
1+
[![](https://img.shields.io/github/stars/javadev/LeetCode-in-Kotlin?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin)
2+
[![](https://img.shields.io/github/forks/javadev/LeetCode-in-Kotlin?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-Kotlin/fork)
3+
4+
## 2002\. Maximum Product of the Length of Two Palindromic Subsequences
5+
6+
Medium
7+
8+
Given a string `s`, find two **disjoint palindromic subsequences** of `s` such that the **product** of their lengths is **maximized**. The two subsequences are **disjoint** if they do not both pick a character at the same index.
9+
10+
Return _the **maximum** possible **product** of the lengths of the two palindromic subsequences_.
11+
12+
A **subsequence** is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters. A string is **palindromic** if it reads the same forward and backward.
13+
14+
**Example 1:**
15+
16+
![example-1](https://assets.leetcode.com/uploads/2021/08/24/two-palindromic-subsequences.png)
17+
18+
**Input:** s = "leetcodecom"
19+
20+
**Output:** 9
21+
22+
**Explanation:** An optimal solution is to choose "ete" for the 1<sup>st</sup> subsequence and "cdc" for the 2<sup>nd</sup> subsequence.
23+
24+
The product of their lengths is: 3 \* 3 = 9.
25+
26+
**Example 2:**
27+
28+
**Input:** s = "bb"
29+
30+
**Output:** 1
31+
32+
**Explanation:** An optimal solution is to choose "b" (the first character) for the 1<sup>st</sup> subsequence and "b" (the second character) for the 2<sup>nd</sup> subsequence.
33+
34+
The product of their lengths is: 1 \* 1 = 1.
35+
36+
**Example 3:**
37+
38+
**Input:** s = "accbcaxxcxx"
39+
40+
**Output:** 25
41+
42+
**Explanation:** An optimal solution is to choose "accca" for the 1<sup>st</sup> subsequence and "xxcxx" for the 2<sup>nd</sup> subsequence.
43+
44+
The product of their lengths is: 5 \* 5 = 25.
45+
46+
**Constraints:**
47+
48+
* `2 <= s.length <= 12`
49+
* `s` consists of lowercase English letters only.
50+
51+
## Solution
52+
53+
```kotlin
54+
class Solution {
55+
fun maxProduct(s: String): Int {
56+
if (s.length == 2) {
57+
return 1
58+
}
59+
val list: MutableList<State> = ArrayList()
60+
val chars = s.toCharArray()
61+
val visited: MutableSet<State> = HashSet()
62+
for (i in chars.indices) {
63+
val mask = 1 shl i
64+
recur(chars, State(i, i, 0, mask), list, visited)
65+
recur(chars, State(i, i + 1, 0, mask), list, visited)
66+
}
67+
list.sortWith { a: State, b: State -> b.cnt - a.cnt }
68+
var res = 1
69+
val explored: MutableSet<Int> = HashSet()
70+
for (i in 0 until list.size - 1) {
71+
if (explored.contains(i)) {
72+
continue
73+
}
74+
val cur = list[i]
75+
if (cur.cnt == 1) {
76+
break
77+
}
78+
for (j in i + 1 until list.size) {
79+
val cand = list[j]
80+
if (cur.mask and cand.mask < 1) {
81+
if (explored.add(j)) {
82+
res = res.coerceAtLeast(cur.cnt * cand.cnt)
83+
}
84+
break
85+
}
86+
}
87+
}
88+
return res
89+
}
90+
91+
private fun recur(chars: CharArray, s: State, list: MutableList<State>, visited: MutableSet<State>) {
92+
if (s.i < 0 || s.j >= chars.size) {
93+
return
94+
}
95+
if (!visited.add(s)) {
96+
return
97+
}
98+
if (chars[s.i] == chars[s.j]) {
99+
val m = s.mask or (1 shl s.i) or (1 shl s.j)
100+
val nextCnt = s.cnt + if (s.i < s.j) 2 else 1
101+
list.add(State(s.i, s.j, nextCnt, m))
102+
recur(chars, State(s.i - 1, s.j + 1, nextCnt, m), list, visited)
103+
}
104+
recur(chars, State(s.i - 1, s.j, s.cnt, s.mask), list, visited)
105+
recur(chars, State(s.i, s.j + 1, s.cnt, s.mask), list, visited)
106+
}
107+
108+
private class State(var i: Int, var j: Int, var cnt: Int, var mask: Int) {
109+
override fun equals(other: Any?): Boolean {
110+
if (other == null || other.javaClass != this.javaClass) {
111+
return false
112+
}
113+
val s = other as State
114+
return i == s.i && j == s.j && mask == s.mask
115+
}
116+
117+
override fun hashCode(): Int {
118+
return (i * 31 + j) * 31 + mask
119+
}
120+
}
121+
}
122+
```

0 commit comments

Comments
 (0)