question_slug
stringlengths
3
77
title
stringlengths
1
183
slug
stringlengths
12
45
summary
stringlengths
1
160
author
stringlengths
2
30
certification
stringclasses
2 values
created_at
stringdate
2013-10-25 17:32:12
2025-04-12 09:38:24
updated_at
stringdate
2013-10-25 17:32:12
2025-04-12 09:38:24
hit_count
int64
0
10.6M
has_video
bool
2 classes
content
stringlengths
4
576k
upvotes
int64
0
11.5k
downvotes
int64
0
358
tags
stringlengths
2
193
comments
int64
0
2.56k
minimum-number-of-days-to-disconnect-island
Simple solution ✨✨
simple-solution-by-sobhandevp2021-zcc3
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
sobhandevp2021
NORMAL
2024-08-11T07:26:02.864804+00:00
2024-08-11T07:26:02.864838+00:00
38
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n int[] row = { 1, -1, 0, 0 };\n int[] col = { 0, 0, 1, -1 };\n \n\n public int minDays(int[][] grid) {\n\n if (count(grid) != 1)\n return 0;\n int n = grid.length;\n int m = grid[0].length;\n for (int i = 0; i < n; i++) {\n for (int j = 0; j < m; j++) {\n if (grid[i][j] == 1) {\n grid[i][j] = 0;\n if (count(grid) != 1)\n return 1;\n grid[i][j] = 1;\n }\n }\n }\n\n return 2;\n }\n\n private int count(int[][] grid) {\n int n = grid.length;\n int m = grid[0].length;\n int isLand = 0;\n boolean[][] vis = new boolean[n][m];\n for (int i = 0; i < n; i++) {\n for (int j = 0; j < m; j++) {\n if (grid[i][j] == 1 && !vis[i][j]) {\n dfs(grid, i, j, vis);\n isLand++;\n }\n }\n }\n return isLand;\n }\n\n private void dfs(int[][] grid, int r, int c, boolean[][] vis) {\n vis[r][c] = true;\n int temp = 0;\n for (int i = 0; i < 4; i++) {\n int tr = r + row[i];\n int tc = c + col[i];\n\n if (tr >= 0 && tc >= 0 && tr < grid.length && tc < grid[0].length && grid[tr][tc] == 1 && !vis[tr][tc]) {\n\n dfs(grid, tr, tc, vis);\n }\n }\n\n }\n}\n```
1
0
['Array', 'Backtracking', 'Depth-First Search', 'Matrix', 'Java']
0
minimum-number-of-days-to-disconnect-island
Focus on DFS only -> YOU WIN😎
focus-on-dfs-only-you-win-by-hacker363-v0n1
\u2B06IF IT HELPS, PLEASE DO UPVOTE \u2B06\n\n# Code\n\nclass Solution:\n def minDays(self, grid: List[List[int]]) -> int:\n temp = copy.deepcopy(grid
hacker363
NORMAL
2024-08-11T07:12:26.469694+00:00
2024-08-11T07:14:50.028591+00:00
9
false
**\u2B06IF IT HELPS, PLEASE DO UPVOTE \u2B06**\n\n# Code\n```\nclass Solution:\n def minDays(self, grid: List[List[int]]) -> int:\n temp = copy.deepcopy(grid)\n\n def isvalid(x,y):\n return 0<=x<len(grid) and 0<=y<len(grid[0]) and grid[x][y]==1\n\n def dfs(x,y):\n grid[x][y] = 2\n moves = [(1,0),(0,1),(-1,0),(0,-1)]\n for dx,dy in moves:\n nx = x+dx\n ny = y+dy\n if isvalid(nx,ny):\n dfs(nx,ny)\n \n def check():\n connected = 0\n for i in range(len(grid)):\n for j in range(len(grid[0])):\n if grid[i][j]==1:\n dfs(i,j)\n connected +=1\n return connected==1\n\n if not check():\n return 0\n\n\n for i in range(len(grid)):\n for j in range(len(grid[0])):\n if temp[i][j] == 1:\n grid = copy.deepcopy(temp)\n grid[i][j] = 0\n if not check():\n return 1\n\n return 2\n```\n**\u2B06IF IT HELPS, PLEASE DO UPVOTE \u2B06**\n
1
0
['Python3']
0
minimum-number-of-days-to-disconnect-island
Tarjans's Algorithm explained 💡 | Detailed explanation ever existed✨ | Beginner friendly🚀
tarjanss-algorithm-explained-detailed-ex-qq8i
Approach : Tarjan\'s Algorithm\n\n## Intuition\n\nAn articulation point is a cell that will split an island in two when it is changed from land to water. If a g
prakhar_arya
NORMAL
2024-08-11T07:02:46.985529+00:00
2024-08-11T07:02:46.985559+00:00
254
false
# Approach : Tarjan\'s Algorithm\n\n## Intuition\n\nAn articulation point is a cell that will split an island in two when it is changed from land to water. If a given grid has an articulation point, we can disconnect the island in one day. Tarjan\'s algorithm efficiently finds articulation points in a graph.\n\nThe algorithm uses three key pieces of information for each node (cell): discovery time, lowest reachable time, and parent. The discovery time is when a node is first visited during the DFS. The lowest reachable time is the minimum discovery time of any node that can be reached from the subtree rooted at the current node, including the current node itself. The parent is the node from which the current node was discovered during the DFS.\n\nA node can be an articulation point in two cases:\n\n1. A non-root node is an articulation point if it has a child whose lowest reachable time is greater than or equal to the node\'s discovery time. This condition means that the child (and its subtree) cannot reach any ancestor of the current node without going through the current node, making it critical for connectivity.\n2. The root node of the DFS tree is an articulation point if it has more than one child. Removing the root would disconnect these children from each other.\n\nIf no articulation points are found, the grid cannot be disconnected by removing a single land cell. In that case, we return 2.\n\n#### Algorithm\n\n- Define a constant array `DIRECTIONS` that contains the directions for moving right, down, left, and up.\n\nMain method `minDays`:\n\n- Set `rows` and `cols` as the number of rows and columns in the `grid`.\n- Initialize an `ArticulationPointInfo` object `apInfo` with `hasArticulationPoint` set to `false` and `time` set to `0`.\n- Initialize variables:\n - `landCells` to count the number of land cells in the grid.\n - `islandCount` to count the number of islands in the grid.\n- Initialize arrays `discoveryTime`, `lowestReachable`, and `parentCell` with default values of `-1`. These arrays store information about each cell during DFS traversal.\n- Loop through each cell `(i, j)` of the `grid`:\n - If the cell is land (`1`):\n - Increment the `landCells` count.\n - If the cell has not been visited (`discoveryTime[i][j]` = `-1`):\n - Call `findArticulationPoints` on `(i, j)` to find if articulation point exists.\n - Increment `islandCount`.\n- If there is zero or more than one island, return `0`\n- If there is only one land cell, return `1`.\n- If there is an articulation point, return `1`.\n- Otherwise, return `2`.\n\nHelper method `findArticulationPoints`:\n\n- Define a method `findArticulationPoints` with parameters: `grid`, the `row` and `col` indices, `discoveryTime`, `lowestReachable`, `parentCell`, and `apInfo`.\n- Set `rows` and `cols` as the number of rows and columns in the `grid`.\n- Set `discoveryTime` of the current cell to `apInfo.time`.\n- Increment the `time` in `apInfo`.\n- Set the `lowestReachable` time of the current cell to its `discoveryTime`.\n- Initialize a variable `children` to count the number of child nodes in the DFS tree.\n- To explore adjacent cells, loop through each `direction` in `DIRECTIONS`:\n - Calculate `newRow` as `row + direction[0]`.\n - Calculate `newCol` as `col + direction[1]`.\n - If `(newRow, newCol)` is a valid cell:\n - If the `discoveryTime` of the new cell is `-1`:\n - Increment `children`.\n - Set the `parentCell` of the new cell to the current cell.\n - Recursively call `findArticulationPoints` for the new cell.\n - Update the `lowestReachable` time for the current cell to the minimum of `lowestReachable[row][col]` and `lowestReachable[newRow][newCol]`.\n - If `lowestReachable` of `(newRow, newCol)` is greater than or equal to `discoveryTime` of `(row, col)`, and `(row, col)` has a parent:\n - Set `hasArticulationPoint` of `apInfo` to `true`.\n - Else if `(newRow, newCol)` is not the parent of `(row, col)`:\n - Set `lowestReachable` time of `(row, col)` to the minimum of `lowestReachable[row][col]` and `discoveryTime[newRow][newCol]`.\n- Check if `(row, col)` is the root of the DFS tree and has more than 1 `children`:\n - Set `hasArticulationPoint` of `apInfo` to `true`.\n\nHelper method `isValidLandCell`:\n\n- Define a method `isValidLandCell` with parameters: `grid`, and the `row` and `col` indices.\n- Return `true` if the given cell is within the bounds of the grid and is a land cell (`1`).\n- Else, return `false`.\n\nHelper class `ArticulationPointInfo`:\n\n- Define a class `ArticulationPointInfo` with fields: `hasArticulationPoint` and `time`.\n- Override the default constructor to initialize `hasArticulationPoint` and `time`.\n\n## Implementation\n```java []\nclass Solution {\n\n // Directions for adjacent cells: right, down, left, up\n private static final int[][] DIRECTIONS = {\n { 0, 1 },\n { 1, 0 },\n { 0, -1 },\n { -1, 0 },\n };\n\n public int minDays(int[][] grid) {\n int rows = grid.length, cols = grid[0].length;\n ArticulationPointInfo apInfo = new ArticulationPointInfo(false, 0);\n int landCells = 0, islandCount = 0;\n\n // Arrays to store information for each cell\n int[][] discoveryTime = new int[rows][cols]; // Time when a cell is first discovered\n int[][] lowestReachable = new int[rows][cols]; // Lowest discovery time reachable from the subtree rooted at\n // this cell\n int[][] parentCell = new int[rows][cols]; // Parent of each cell in DFS tree\n\n // Initialize arrays with default values\n for (int i = 0; i < rows; i++) {\n Arrays.fill(discoveryTime[i], -1);\n Arrays.fill(lowestReachable[i], -1);\n Arrays.fill(parentCell[i], -1);\n }\n\n // Traverse the grid to find islands and articulation points\n for (int i = 0; i < rows; i++) {\n for (int j = 0; j < cols; j++) {\n if (grid[i][j] == 1) {\n landCells++;\n if (discoveryTime[i][j] == -1) { // If not yet visited\n // Start DFS for a new island\n findArticulationPoints(\n grid,\n i,\n j,\n discoveryTime,\n lowestReachable,\n parentCell,\n apInfo\n );\n islandCount++;\n }\n }\n }\n }\n\n // Determine the minimum number of days to disconnect the grid\n if (islandCount == 0 || islandCount >= 2) return 0; // Already disconnected or no land\n if (landCells == 1) return 1; // Only one land cell\n if (apInfo.hasArticulationPoint) return 1; // An articulation point exists\n return 2; // Need to remove any two land cells\n }\n\n private void findArticulationPoints(\n int[][] grid,\n int row,\n int col,\n int[][] discoveryTime,\n int[][] lowestReachable,\n int[][] parentCell,\n ArticulationPointInfo apInfo\n ) {\n int rows = grid.length, cols = grid[0].length;\n discoveryTime[row][col] = apInfo.time;\n apInfo.time++;\n lowestReachable[row][col] = discoveryTime[row][col];\n int children = 0;\n\n // Explore all adjacent cells\n for (int[] direction : DIRECTIONS) {\n int newRow = row + direction[0];\n int newCol = col + direction[1];\n if (isValidLandCell(grid, newRow, newCol)) {\n if (discoveryTime[newRow][newCol] == -1) {\n children++;\n parentCell[newRow][newCol] = row * cols + col; // Set parent\n findArticulationPoints(\n grid,\n newRow,\n newCol,\n discoveryTime,\n lowestReachable,\n parentCell,\n apInfo\n );\n\n // Update lowest reachable time\n lowestReachable[row][col] = Math.min(\n lowestReachable[row][col],\n lowestReachable[newRow][newCol]\n );\n\n // Check for articulation point condition\n if (\n lowestReachable[newRow][newCol] >=\n discoveryTime[row][col] &&\n parentCell[row][col] != -1\n ) {\n apInfo.hasArticulationPoint = true;\n }\n } else if (newRow * cols + newCol != parentCell[row][col]) {\n // Update lowest reachable time for back edge\n lowestReachable[row][col] = Math.min(\n lowestReachable[row][col],\n discoveryTime[newRow][newCol]\n );\n }\n }\n }\n\n // Root of DFS tree is an articulation point if it has more than one child\n if (parentCell[row][col] == -1 && children > 1) {\n apInfo.hasArticulationPoint = true;\n }\n }\n\n // Check if the given cell is a valid land cell\n private boolean isValidLandCell(int[][] grid, int row, int col) {\n int rows = grid.length, cols = grid[0].length;\n return (\n row >= 0 &&\n col >= 0 &&\n row < rows &&\n col < cols &&\n grid[row][col] == 1\n );\n }\n\n private class ArticulationPointInfo {\n\n boolean hasArticulationPoint;\n int time;\n\n ArticulationPointInfo(boolean hasArticulationPoint, int time) {\n this.hasArticulationPoint = hasArticulationPoint;\n this.time = time;\n }\n }\n}\n```\n```python []\nclass Solution:\n # Directions for adjacent cells: right, down, left, up\n DIRECTIONS = [[0, 1], [1, 0], [0, -1], [-1, 0]]\n\n def minDays(self, grid):\n rows, cols = len(grid), len(grid[0])\n ap_info = {"has_articulation_point": False, "time": 0}\n land_cells = 0\n island_count = 0\n\n # Arrays to store information for each cell\n discovery_time = [\n [-1] * cols for _ in range(rows)\n ] # Time when a cell is first discovered\n lowest_reachable = [\n [-1] * cols for _ in range(rows)\n ] # Lowest discovery time reachable from the subtree rooted at this cell\n parent_cell = [\n [-1] * cols for _ in range(rows)\n ] # Parent of each cell in DFS tree\n\n def _find_articulation_points(row, col):\n discovery_time[row][col] = ap_info["time"]\n ap_info["time"] += 1\n lowest_reachable[row][col] = discovery_time[row][col]\n children = 0\n\n # Explore all adjacent cells\n for direction in self.DIRECTIONS:\n new_row = row + direction[0]\n new_col = col + direction[1]\n if (\n 0 <= new_row < rows\n and 0 <= new_col < cols\n and grid[new_row][new_col] == 1\n ):\n if discovery_time[new_row][new_col] == -1:\n children += 1\n parent_cell[new_row][new_col] = (\n row * cols + col\n ) # Set parent\n _find_articulation_points(new_row, new_col)\n\n # Update lowest reachable time\n lowest_reachable[row][col] = min(\n lowest_reachable[row][col],\n lowest_reachable[new_row][new_col],\n )\n\n # Check for articulation point condition\n if (\n lowest_reachable[new_row][new_col]\n >= discovery_time[row][col]\n and parent_cell[row][col] != -1\n ):\n ap_info["has_articulation_point"] = True\n elif new_row * cols + new_col != parent_cell[row][col]:\n # Update lowest reachable time for back edge\n lowest_reachable[row][col] = min(\n lowest_reachable[row][col],\n discovery_time[new_row][new_col],\n )\n\n # Root of DFS tree is an articulation point if it has more than one child\n if parent_cell[row][col] == -1 and children > 1:\n ap_info["has_articulation_point"] = True\n\n # Traverse the grid to find islands and articulation points\n for i in range(rows):\n for j in range(cols):\n if grid[i][j] == 1:\n land_cells += 1\n if discovery_time[i][j] == -1: # If not yet visited\n # Start DFS for a new island\n _find_articulation_points(i, j)\n island_count += 1\n\n # Determine the minimum number of days to disconnect the grid\n if island_count == 0 or island_count >= 2:\n return 0 # Already disconnected or no land\n if land_cells == 1:\n return 1 # Only one land cell\n if ap_info["has_articulation_point"]:\n return 1 # An articulation point exists\n return 2 # Need to remove any two land cells\n```\n```c++ []\nclass Solution {\nprivate:\n // Directions for adjacent cells: right, down, left, up\n const vector<vector<int>> DIRECTIONS = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};\n\n struct ArticulationPointInfo {\n bool hasArticulationPoint;\n int time;\n\n ArticulationPointInfo(bool hasArticulationPoint, int time)\n : hasArticulationPoint(hasArticulationPoint), time(time) {}\n };\n\npublic:\n int minDays(vector<vector<int>>& grid) {\n int rows = grid.size(), cols = grid[0].size();\n ArticulationPointInfo apInfo(false, 0);\n int landCells = 0, islandCount = 0;\n\n // Arrays to store information for each cell\n vector<vector<int>> discoveryTime(\n rows,\n vector<int>(cols, -1)); // Time when a cell is first discovered\n vector<vector<int>> lowestReachable(\n rows,\n vector<int>(cols, -1)); // Lowest discovery time reachable from the\n // subtree rooted at this cell\n vector<vector<int>> parentCell(\n rows, vector<int>(cols, -1)); // Parent of each cell in DFS tree\n\n // Traverse the grid to find islands and articulation points\n for (int i = 0; i < rows; i++) {\n for (int j = 0; j < cols; j++) {\n if (grid[i][j] == 1) {\n landCells++;\n if (discoveryTime[i][j] == -1) { // If not yet visited\n // Start DFS for a new island\n findArticulationPoints(grid, i, j, discoveryTime,\n lowestReachable, parentCell,\n apInfo);\n islandCount++;\n }\n }\n }\n }\n\n // Determine the minimum number of days to disconnect the grid\n if (islandCount == 0 || islandCount >= 2)\n return 0; // Already disconnected or no land\n if (landCells == 1) return 1; // Only one land cell\n if (apInfo.hasArticulationPoint)\n return 1; // An articulation point exists\n return 2; // Need to remove any two land cells\n }\n\nprivate:\n void findArticulationPoints(vector<vector<int>>& grid, int row, int col,\n vector<vector<int>>& discoveryTime,\n vector<vector<int>>& lowestReachable,\n vector<vector<int>>& parentCell,\n ArticulationPointInfo& apInfo) {\n int rows = grid.size(), cols = grid[0].size();\n discoveryTime[row][col] = apInfo.time;\n apInfo.time++;\n lowestReachable[row][col] = discoveryTime[row][col];\n int children = 0;\n\n // Explore all adjacent cells\n for (const auto& direction : DIRECTIONS) {\n int newRow = row + direction[0];\n int newCol = col + direction[1];\n if (isValidLandCell(grid, newRow, newCol)) {\n if (discoveryTime[newRow][newCol] == -1) {\n children++;\n parentCell[newRow][newCol] =\n row * cols + col; // Set parent\n findArticulationPoints(grid, newRow, newCol, discoveryTime,\n lowestReachable, parentCell, apInfo);\n\n // Update lowest reachable time\n lowestReachable[row][col] =\n min(lowestReachable[row][col],\n lowestReachable[newRow][newCol]);\n\n // Check for articulation point condition\n if (lowestReachable[newRow][newCol] >=\n discoveryTime[row][col] &&\n parentCell[row][col] != -1) {\n apInfo.hasArticulationPoint = true;\n }\n } else if (newRow * cols + newCol != parentCell[row][col]) {\n // Update lowest reachable time for back edge\n lowestReachable[row][col] =\n min(lowestReachable[row][col],\n discoveryTime[newRow][newCol]);\n }\n }\n }\n\n // Root of DFS tree is an articulation point if it has more than one\n // child\n if (parentCell[row][col] == -1 && children > 1) {\n apInfo.hasArticulationPoint = true;\n }\n }\n\n // Check if the given cell is a valid land cell\n bool isValidLandCell(const vector<vector<int>>& grid, int row, int col) {\n int rows = grid.size(), cols = grid[0].size();\n return row >= 0 && col >= 0 && row < rows && col < cols &&\n grid[row][col] == 1;\n }\n};\n```\n\n\n## Complexity Analysis\n\nLet m be the number of rows and n be the number of columns in the `grid`.\n\n- Time complexity: $$O(m\u22C5n)$$\n \n Initializing the arrays `discoveryTime`, `lowestReachable`, and `parentCell` takes $$O(m\u22C5n)$$ time each.\n \n The DFS traversal by the `findArticulationPoints` method visits each cell exactly once, taking $$O(m\u22C5n)$$ time.\n \n Thus, the overall time complexity of the algorithm is $$O(m\u22C5n)$$.\n \n- Space complexity: $$O(m\u22C5n)$$\n \n The arrays `discoveryTime`, `lowestReachable`, and `parentCell` each take $$O(m\u22C5n)$$ space.\n \n The recursive call stack for the DFS traversal can go as deep as the number of land cells in the worst case. If all cells are land, the depth of the recursive call stack can be $$O(m\u22C5n)$$.\n \n Thus, the total space complexity of the algorithm is O(m\u22C5n)+O(m\u22C5n)=$$O(m\u22C5n)$$.\n\n# Code\n```\nclass Solution {\n\n // Directions for adjacent cells: right, down, left, up\n private static final int[][] DIRECTIONS = {\n { 0, 1 },\n { 1, 0 },\n { 0, -1 },\n { -1, 0 },\n };\n\n public int minDays(int[][] grid) {\n int rows = grid.length, cols = grid[0].length;\n ArticulationPointInfo apInfo = new ArticulationPointInfo(false, 0);\n int landCells = 0, islandCount = 0;\n\n // Arrays to store information for each cell\n int[][] discoveryTime = new int[rows][cols]; // Time when a cell is first discovered\n int[][] lowestReachable = new int[rows][cols]; // Lowest discovery time reachable from the subtree rooted at\n // this cell\n int[][] parentCell = new int[rows][cols]; // Parent of each cell in DFS tree\n\n // Initialize arrays with default values\n for (int i = 0; i < rows; i++) {\n Arrays.fill(discoveryTime[i], -1);\n Arrays.fill(lowestReachable[i], -1);\n Arrays.fill(parentCell[i], -1);\n }\n\n // Traverse the grid to find islands and articulation points\n for (int i = 0; i < rows; i++) {\n for (int j = 0; j < cols; j++) {\n if (grid[i][j] == 1) {\n landCells++;\n if (discoveryTime[i][j] == -1) { // If not yet visited\n // Start DFS for a new island\n findArticulationPoints(\n grid,\n i,\n j,\n discoveryTime,\n lowestReachable,\n parentCell,\n apInfo\n );\n islandCount++;\n }\n }\n }\n }\n\n // Determine the minimum number of days to disconnect the grid\n if (islandCount == 0 || islandCount >= 2) return 0; // Already disconnected or no land\n if (landCells == 1) return 1; // Only one land cell\n if (apInfo.hasArticulationPoint) return 1; // An articulation point exists\n return 2; // Need to remove any two land cells\n }\n\n private void findArticulationPoints(\n int[][] grid,\n int row,\n int col,\n int[][] discoveryTime,\n int[][] lowestReachable,\n int[][] parentCell,\n ArticulationPointInfo apInfo\n ) {\n int rows = grid.length, cols = grid[0].length;\n discoveryTime[row][col] = apInfo.time;\n apInfo.time++;\n lowestReachable[row][col] = discoveryTime[row][col];\n int children = 0;\n\n // Explore all adjacent cells\n for (int[] direction : DIRECTIONS) {\n int newRow = row + direction[0];\n int newCol = col + direction[1];\n if (isValidLandCell(grid, newRow, newCol)) {\n if (discoveryTime[newRow][newCol] == -1) {\n children++;\n parentCell[newRow][newCol] = row * cols + col; // Set parent\n findArticulationPoints(\n grid,\n newRow,\n newCol,\n discoveryTime,\n lowestReachable,\n parentCell,\n apInfo\n );\n\n // Update lowest reachable time\n lowestReachable[row][col] = Math.min(\n lowestReachable[row][col],\n lowestReachable[newRow][newCol]\n );\n\n // Check for articulation point condition\n if (\n lowestReachable[newRow][newCol] >=\n discoveryTime[row][col] &&\n parentCell[row][col] != -1\n ) {\n apInfo.hasArticulationPoint = true;\n }\n } else if (newRow * cols + newCol != parentCell[row][col]) {\n // Update lowest reachable time for back edge\n lowestReachable[row][col] = Math.min(\n lowestReachable[row][col],\n discoveryTime[newRow][newCol]\n );\n }\n }\n }\n\n // Root of DFS tree is an articulation point if it has more than one child\n if (parentCell[row][col] == -1 && children > 1) {\n apInfo.hasArticulationPoint = true;\n }\n }\n\n // Check if the given cell is a valid land cell\n private boolean isValidLandCell(int[][] grid, int row, int col) {\n int rows = grid.length, cols = grid[0].length;\n return (\n row >= 0 &&\n col >= 0 &&\n row < rows &&\n col < cols &&\n grid[row][col] == 1\n );\n }\n\n private class ArticulationPointInfo {\n\n boolean hasArticulationPoint;\n int time;\n\n ArticulationPointInfo(boolean hasArticulationPoint, int time) {\n this.hasArticulationPoint = hasArticulationPoint;\n this.time = time;\n }\n }\n}\n```
1
0
['Array', 'Depth-First Search', 'Breadth-First Search', 'Strongly Connected Component', 'Python', 'C++', 'Java', 'Python3']
1
minimum-number-of-days-to-disconnect-island
Implementation in Java || DFS || Good Complexity 🧑‍💻🧑‍💻🧑‍💻
implementation-in-java-dfs-good-complexi-ycvo
Intuition\n Describe your first thoughts on how to solve this problem. \n\nTo solve the problem of determining the minimum number of days required to disconnect
ritujpr123
NORMAL
2024-08-11T06:03:13.796694+00:00
2024-08-11T06:03:13.796727+00:00
49
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\nTo solve the problem of determining the minimum number of days required to disconnect an initially connected binary grid, we need to consider a few key points:\n\n**1. Connected Grid**: If the grid is already disconnected (i.e., there are multiple islands), then the answer is 0.\n**2. Single Land Cell Removal**: If removing any single land cell results in disconnection, then the answer is 1.\n**3. Two Land Cells Removal:** If no single land cell removal leads to disconnection, then the answer is 2, as removing any two connected land cells will surely disconnect the grid.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n**1. Check Initial Connection:** First, determine if the grid is initially connected. If it\'s not connected, return 0.\n**2. Check Single Cell Removal:** For each land cell, temporarily remove it and check if the grid becomes disconnected. If yes, return 1.\n**3. Check Two Cells Removal:** If the grid remains connected after any single cell removal, return 2.\n\n\n# Code\n```\nclass Solution {\n public int minDays(int[][] grid) {\n int m = grid.length, n = grid[0].length;\n \n if (!isConnected(grid, m, n)) {\n return 0; // Already disconnected\n }\n \n // Try removing each land cell to see if it disconnects the grid\n for (int i = 0; i < m; i++) {\n for (int j = 0; j < n; j++) {\n if (grid[i][j] == 1) {\n grid[i][j] = 0; // Temporarily remove this cell\n if (!isConnected(grid, m, n)) {\n return 1; // Grid is disconnected after removing this cell\n }\n grid[i][j] = 1; // Restore the cell\n }\n }\n }\n \n return 2; // If we cannot disconnect by removing one cell, the answer is 2\n }\n \n // Helper method to check if the grid is connected\n private boolean isConnected(int[][] grid, int m, int n) {\n boolean[][] visited = new boolean[m][n];\n int[] start = findFirstLand(grid, m, n);\n \n if (start == null) {\n return false; // No land at all\n }\n \n dfs(grid, visited, start[0], start[1], m, n);\n \n for (int i = 0; i < m; i++) {\n for (int j = 0; j < n; j++) {\n if (grid[i][j] == 1 && !visited[i][j]) {\n return false; // Found unvisited land, hence disconnected\n }\n }\n }\n return true;\n }\n \n // DFS to mark all connected land\n private void dfs(int[][] grid, boolean[][] visited, int x, int y, int m, int n) {\n if (x < 0 || x >= m || y < 0 || y >= n || grid[x][y] == 0 || visited[x][y]) {\n return;\n }\n visited[x][y] = true;\n dfs(grid, visited, x + 1, y, m, n);\n dfs(grid, visited, x - 1, y, m, n);\n dfs(grid, visited, x, y + 1, m, n);\n dfs(grid, visited, x, y - 1, m, n);\n }\n \n // Find the first land cell\n private int[] findFirstLand(int[][] grid, int m, int n) {\n for (int i = 0; i < m; i++) {\n for (int j = 0; j < n; j++) {\n if (grid[i][j] == 1) {\n return new int[]{i, j};\n }\n }\n }\n return null; // No land found\n }\n}\n\n```
1
0
['Java']
0
minimum-number-of-days-to-disconnect-island
Easy solution.
easy-solution-by-lcb_2022039-s4qz
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
LCB_2022039
NORMAL
2024-08-11T05:56:03.334069+00:00
2024-08-11T05:56:03.334100+00:00
17
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO((n\u2217m)^2)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(n*m)\n\n# Code\n```\nclass Solution {\npublic:\n int n, m;\n vector<vector<int>> directions = {{0, 1}, {1, 0}, {-1, 0}, {0, -1}};\n \n bool isvalid(int i, int j) {\n return i >= 0 && i < n && j >= 0 && j < m;\n }\n\n void dfs(vector<vector<int>>& grid, vector<vector<bool>>& visited, int i, int j) {\n visited[i][j] = true;\n for (auto dir : directions) {\n int i_ = i + dir[0];\n int j_ = j + dir[1];\n if (isvalid(i_, j_) && !visited[i_][j_] && grid[i_][j_] == 1) {\n dfs(grid, visited, i_, j_);\n }\n }\n }\n \n int countIslands(vector<vector<int>>& grid) {\n vector<vector<bool>> visited(n, vector<bool>(m, false));\n int island = 0;\n for (int i = 0; i < n; i++) {\n for (int j = 0; j < m; j++) {\n if (grid[i][j] == 1 && !visited[i][j]) {\n dfs(grid, visited, i, j);\n island++;\n }\n }\n }\n return island;\n }\n\n int minDays(vector<vector<int>>& grid) {\n n = grid.size();\n m = grid[0].size();\n \n // Step 1: Check how many islands there are initially\n int island = countIslands(grid);\n if (island != 1) {\n return 0;\n }\n\n // Step 2: Try removing each land cell and see if it disconnects the island\n for (int i = 0; i < n; i++) {\n for (int j = 0; j < m; j++) {\n if (grid[i][j] == 1) {\n grid[i][j] = 0; // Remove this cell\n int newIslands = countIslands(grid);\n grid[i][j] = 1; // Restore the cell\n \n if (newIslands > 1 || newIslands == 0) {\n return 1;\n }\n }\n }\n }\n \n return 2;\n }\n};\n\n```
1
0
['Array', 'Depth-First Search', 'Matrix', 'Strongly Connected Component', 'C++']
0
minimum-number-of-days-to-disconnect-island
Simplest way to solve this using JavaScript 🔥
simplest-way-to-solve-this-using-javascr-4y3u
Intuition\nThe problem involves finding the minimum number of days required to disconnect an island in a binary grid. My first thought is that the problem can b
kushh23
NORMAL
2024-08-11T05:43:41.463495+00:00
2024-08-11T05:43:41.463525+00:00
44
false
# Intuition\nThe problem involves finding the minimum number of days required to disconnect an island in a binary grid. My first thought is that the problem can be approached by checking the connectivity of the grid. By trying to remove each land cell and checking if the grid becomes disconnected, I can determine the minimum number of cells that need to be converted to water to achieve disconnection.\n\n# Approach\n1. Initial Check: First, check if the grid is already disconnected by counting the number of islands using a DFS approach. If the grid has more than one island, it\'s already disconnected, so return 0.\n\n2. Single Cell Removal: If the grid is connected (i.e., has exactly one island), iterate over all land cells. For each land cell, convert it to water temporarily and check if this action disconnects the grid. If it does, return 1 because disconnection is achieved in one day.\n\n3. Two Cells Removal: If no single land cell removal leads to disconnection, return 2. This is because, in the worst case, you need to remove at least two cells to disconnect the grid.\n\n# Complexity\n- Time complexity: O((m\xD7n)\xD7(m\xD7n))O((m\xD7n)\xD7(m\xD7n))\n\n- Space complexity: O(m\xD7n)\n\n# Code\n```\n/**\n * @param {number[][]} grid\n * @return {number}\n */\nvar minDays = function(grid) {\n const m = grid.length;\n const n = grid[0].length;\n\n function countIslands() {\n let visited = Array.from({ length: m }, () => Array(n).fill(false));\n let islandCount = 0;\n\n function dfs(x, y) {\n if (x < 0 || y < 0 || x >= m || y >= n || grid[x][y] === 0 || visited[x][y]) {\n return;\n }\n visited[x][y] = true;\n dfs(x + 1, y);\n dfs(x - 1, y);\n dfs(x, y + 1);\n dfs(x, y - 1);\n }\n\n for (let i = 0; i < m; i++) {\n for (let j = 0; j < n; j++) {\n if (grid[i][j] === 1 && !visited[i][j]) {\n islandCount++;\n dfs(i, j);\n }\n }\n }\n return islandCount;\n }\n\n if (countIslands() !== 1) return 0;\n\n for (let i = 0; i < m; i++) {\n for (let j = 0; j < n; j++) {\n if (grid[i][j] === 1) {\n grid[i][j] = 0;\n if (countIslands() !== 1) return 1;\n grid[i][j] = 1;\n }\n }\n }\n return 2;\n};\n```
1
0
['JavaScript']
0
minimum-number-of-days-to-disconnect-island
Top One Ranking Code || optimised code || easy to understand
top-one-ranking-code-optimised-code-easy-irck
Code\n\nclass Solution {\n int time;\n int[][] vis;\n int[][] low;\n int[] d=new int[]{0,1,0,-1,0};\n boolean arti;\n public int minDays(int[]
ruchapatil18
NORMAL
2024-08-11T05:10:50.102611+00:00
2024-08-11T05:10:50.102641+00:00
8
false
# Code\n```\nclass Solution {\n int time;\n int[][] vis;\n int[][] low;\n int[] d=new int[]{0,1,0,-1,0};\n boolean arti;\n public int minDays(int[][] grid) {\n int n=grid.length;\n int m=grid[0].length;\n arti=false;\n vis=new int[n][m];\n low=new int[n][m];\n time=1;\n boolean hasArt=false;\n boolean found=false;\n for(int i=0;i<n;i++){\n for(int j=0;j<m;j++){\n if(grid[i][j]==1){\n if(found)\n return 0;\n found=true;\n art(i,j,grid,-100,-100);\n }\n }\n }\n\n if(time==1)\n return 0;\n\n if(time==2)\n return 1;\n if(arti)\n return 1;\n else\n return 2;\n }\n\n public void art(int row,int col,int[][] grid , int parRow,int parCol){\n grid[row][col]=0;\n vis[row][col]=time;\n low[row][col]=time;\n time++;\n int child=0;\n for(int i=0;i<4;i++){\n int x=d[i]+row;\n int y=d[i+1]+col;\n\n if(x<0 || y<0 || x>=grid.length || y>=grid[0].length || (x==parRow && y==parCol) || (vis[x][y]==0 && grid[x][y]==0))\n continue;\n if(vis[x][y]==0){\n child++;\n art(x,y,grid,row,col);\n low[row][col]=Math.min(low[row][col],low[x][y]);\n if(low[x][y]>=vis[row][col] && (parRow!=-100 && parCol!=-100))\n arti=true;\n }else{\n low[row][col]=Math.min(low[row][col],vis[x][y]);\n }\n }\n\n if(parRow==-100 && parCol==-100 && child>1)\n arti=true;\n }\n}\n```
1
0
['Java']
0
find-the-maximum-sequence-value-of-array
L2R and R2L
l2r-and-r2l-by-votrubac-rytj
We find all possible OR values for the left subsequence.\n\n> We use take/not take DFS with memoisation. \n\nOnce we take k numbers, we track the earliest posit
votrubac
NORMAL
2024-09-14T18:01:08.846010+00:00
2024-09-15T17:02:39.305269+00:00
2,662
false
We find all possible OR values for the left subsequence.\n\n> We use take/not take DFS with memoisation. \n\nOnce we take `k` numbers, we track the **earliest** position `i` for the OR value.\n\nThen we do the same for the right subsequence.\n\n\nThis time, however, we go right-to-left, and store the **latest** position for each OR value we found.\n\nNow, we check all combinations of left and right OR values.\n\nIf the left OR value appears before the right one, the subsequences do not overlap and we can do XOR.\n\n**C++**\n```cpp\nbool dp1[401][201][128] = {}, dp2[401][201][128] = {};\nvoid dfs1(int i, vector<int>& nums, int cnt, int k, int cur, vector<int> &vals) {\n if (cnt == 0)\n vals[cur] = min(vals[cur], i - 1);\n else if (i + k < nums.size() && !dp1[i][cnt][cur]) {\n dp1[i][cnt][cur] = true;\n dfs1(i + 1, nums, cnt, k, cur, vals);\n dfs1(i + 1, nums, cnt - 1, k, cur | nums[i], vals); \n }\n}\nvoid dfs2(int i, vector<int>& nums, int cnt, int k, int cur, vector<int> &vals) {\n if (cnt == 0)\n vals[cur] = max(vals[cur], i + 1); \n else if (i >= k && !dp2[i][cnt][cur]) {\n dp2[i][cnt][cur] = true;\n dfs2(i - 1, nums, cnt, k, cur, vals);\n dfs2(i - 1, nums, cnt - 1, k, cur | nums[i], vals); \n }\n}\nint maxValue(vector<int>& nums, int k) {\n int res = 0;\n vector<int> vals1(128, INT_MAX), vals2(128);\n dfs1(0, nums, k, k, 0, vals1);\n dfs2(nums.size() - 1, nums, k, k, 0, vals2);\n for (int i = 0; i < 128; ++i)\n for (int j = 0; j < 128; ++j)\n if (vals1[i] < vals2[j])\n res = max(res, i ^ j);\n return res;\n}\n```
34
0
['C']
13
find-the-maximum-sequence-value-of-array
DP
dp-by-then00bprogrammer-8klk
Intuition\nTry to calculate every possible OR value till an index of different length subsequences.\n\n# Approach\n1. Use DP with base case dp[0][0][0]=1 (since
then00bprogrammer
NORMAL
2024-09-14T16:02:15.216887+00:00
2024-09-17T06:59:40.010138+00:00
3,655
false
# Intuition\nTry to calculate every possible OR value till an index of different length subsequences.\n\n# Approach\n1. Use DP with base case `dp[0][0][0]=1` (since an empty subsequence has OR zero).\n2. Then for every index we\'ve 2 choices either take that element or not take.\n3. We iterate over all possible OR values (`x`) that could have been achieved before index `i` at a given length `len` (i.e., for subsequences of length `len` before index `i`).\n4. Hence, transitions:\n `Not Take: dp[i][len][x] = dp[i-1][len][x]`\n `Take: dp[i][len][nums[i] | x] |= dp[i-1][len-1][x]`\n5. Now build this table forward and backward, and at every index check every possible combination of ORs of length `k` foward and backward using DP table.\n\n# Complexity\n- Time complexity:\nO(N * K * 129 + N * 129 * 129)\n\n- Space complexity:\nO(N * K * 129)\n\n# Code\n```cpp []\nclass Solution {\n vector<vector<vector<int>>> allPossibleORsTillAnIndex(vector<int>& nums, int k) {\n int n = nums.size();\n vector<vector<vector<int>>> dp(\n n, vector<vector<int>>(k + 1, vector<int>(129)));\n dp[0][1][nums[0]] = 1;\n dp[0][0][0] = 1;\n\n for (int i = 1; i < n; i++) {\n dp[i][0][0] = 1;\n for (int j = 1; j <= k; j++) {\n for (int x = 0; x <= 128; x++) {\n if (!dp[i][j][x])\n dp[i][j][x] = dp[i - 1][j][x];\n int next = nums[i] | x;\n if (dp[i - 1][j - 1][x])\n dp[i][j][next] = dp[i - 1][j - 1][x];\n }\n }\n }\n return dp;\n }\n\npublic:\n int maxValue(vector<int>& nums, int k) {\n vector<vector<vector<int>>> left = allPossibleORsTillAnIndex(nums, k);\n reverse(begin(nums), end(nums));\n vector<vector<vector<int>>> right = allPossibleORsTillAnIndex(nums, k);\n reverse(begin(right), end(right));\n int n = nums.size();\n int res = 0;\n for (int i = k - 1; i + k < nums.size(); i++) {\n for (int a = 0; a <= 128; a++) {\n for (int b = 0; b <= 128; b++) {\n if (left[i][k][a] && right[i + 1][k][b]) {\n res = max(res, a ^ b);\n }\n }\n }\n }\n return res;\n }\n};\n```
33
5
['Dynamic Programming', 'Prefix Sum', 'C++']
9
find-the-maximum-sequence-value-of-array
[Python] DP
python-dp-by-lee215-ls2r
Intuition\nIt\'s like a knapsack problem, we can take or skip.\n\n\n# Explanation\ndp(i, k, di) returns the possible OR value of k elements\nin A[i], A[i +/- 1]
lee215
NORMAL
2024-09-16T09:04:02.282995+00:00
2024-09-16T09:04:02.283027+00:00
707
false
# **Intuition**\nIt\'s like a knapsack problem, we can take or skip.\n<br>\n\n# **Explanation**\n`dp(i, k, di)` returns the possible OR value of `k` elements\nin A[i], A[i +/- 1], A[i +/- 2] ...\n\nEnumerate the mid of first `k` elements and last `k` elements,\nbrute check the all pair combination from left and right,\nreturn the max.\n<br>\n\n# **Complexity**\nTime `O(n * k * 128)`\nSpace `O(n * k * 128)`\n<br>\n\n\n**Python**\n```py\n def maxValue(self, A: List[int], k: int) -> int:\n @cache\n def dp(i, k, di):\n if k == 0:\n return {0}\n if i < 0 or i == len(A):\n return set()\n return dp(i + di, k, di) | {v | A[i] for v in dp(i + di, k - 1, di)}\n res = 0\n for i in range(len(A)):\n for a in dp(i, k, -1):\n for b in dp(i + 1, k, 1):\n res = max(res, a ^ b)\n return res\n```\n\n
14
2
['Python']
2
find-the-maximum-sequence-value-of-array
[C++] DP with Prefix and Suffix
c-dp-with-prefix-and-suffix-by-awice-ng9i
Let prefix[v] = n be the least number of elements n from the prefix until there are k of them with an OR value of v. We can calculate this with a DP.\n\n# Code
awice
NORMAL
2024-09-14T16:46:59.606018+00:00
2024-09-14T16:46:59.606044+00:00
1,588
false
Let `prefix[v] = n` be the least number of elements `n` from the prefix until there are `k` of them with an OR value of `v`. We can calculate this with a DP.\n\n# Code\n```cpp []\nclass Solution {\n public:\n int maxValue(vector<int> &A, int K) {\n int N = A.size();\n\n auto make = [&]() {\n map<int, int> first;\n vector<set<int>> dp(K);\n dp[0].insert(0);\n for (int i = 0; i < N; ++i) {\n for (int v : dp[K - 1]) {\n if (!first.count(v | A[i]))\n first[v | A[i]] = i + 1;\n }\n for (int k = K - 2; k >= 0; --k) {\n for (int v : dp[k])\n dp[k + 1].insert(v | A[i]);\n }\n }\n return first;\n };\n\n map<int, int> prefix = make();\n reverse(A.begin(), A.end());\n map<int, int> suffix = make();\n\n int ans = 0;\n for (auto [u, n1] : prefix)\n for (auto [v, n2] : suffix)\n if (n1 + n2 <= N)\n ans = max(ans, u ^ v);\n return ans;\n }\n};\n```
12
0
['C++']
1
find-the-maximum-sequence-value-of-array
✅Detailed explanation🔥beats 100%🔥C++🔥Java🔥Python3🔥
detailed-explanationbeats-100cjavapython-lzds
Problem Restatement\n\nYou need to find the maximum value of any subsequence of nums with size 2 * k. The value of such a sequence is defined as:\n\n\[ \text{Va
aijcoder
NORMAL
2024-09-14T16:14:29.305103+00:00
2024-09-14T17:30:12.832178+00:00
2,351
false
### Problem Restatement\n\nYou need to find the maximum value of any subsequence of `nums` with size `2 * k`. The value of such a sequence is defined as:\n\n\\[ \\text{Value} = ( \\text{OR of first } k \\text{ elements} ) \\text{ XOR } ( \\text{OR of last } k \\text{ elements} ) \\]\n\n### Approach Overview\n\n1. **Dynamic Programming (DP) with Bitmasking**:\n - Use bitmasking to track which elements can form the OR results for any given bitmask.\n - Use DP to compute the minimum number of elements required to achieve each bitmask.\n\n2. **Tracking Valid Sequences**:\n - Use arrays to store the first and last valid positions for sequences that meet the condition for OR and XOR calculations.\n\n### Detailed Explanation\n\n#### 1. **Initialization and Definitions**\n\n- **Variables**:\n - `pre[130]` and `suf[130]`: Arrays to store the first and last indices where a subsequence of length `2 * k` can achieve a specific OR value.\n - `dp[128]`: Array where `dp[mask]` holds the minimum number of elements needed to achieve `mask`.\n - `cnt[128]`: Array to count occurrences of each mask.\n\n#### 2. **Processing the Array (Forward Pass)**\n\n- **Update DP Table**:\n - For each element `A[i]` in `nums`, update the `dp` table:\n ```cpp\n for (int mask = 0; mask < 128; ++mask) {\n dp[mask | A[i]] = min(dp[mask | A[i]], 1 + dp[mask]);\n }\n ```\n This means if `dp[mask]` is the minimum number of elements needed to achieve `mask`, then to achieve `mask | A[i]`, you need one more element, i.e., `1 + dp[mask]`.\n\n- **Count Valid Masks**:\n - For each `mask`, if `A[i]` is a valid submask of `mask`, increment `cnt[mask]`.\n ```cpp\n if (isSubMask(A[i], mask)) cnt[mask]++;\n ```\n\n- **Update `pre` Array**:\n - If `dp[mask] <= k` and `cnt[mask] >= k`, then store the current index `i` as the first index for this mask if it hasn\'t been set yet.\n ```cpp\n if (dp[mask] <= k && cnt[mask] >= k && pre[mask] == -1) {\n pre[mask] = i;\n }\n ```\n\n#### 3. **Processing the Array (Backward Pass)**\n\n- **Reset DP and Count Arrays**:\n - Reinitialize `dp` and `cnt` arrays for the backward pass.\n ```cpp\n dp.assign(128, 1e9);\n cnt.assign(128, 0);\n ```\n\n- **Backward Update DP Table**:\n - Similar to the forward pass, but iterate from the end of the array.\n ```cpp\n for (int mask = 0; mask < 128; ++mask) {\n dp[mask | A[i]] = min(dp[mask | A[i]], 1 + dp[mask]);\n }\n ```\n\n- **Count Valid Masks**:\n - Count occurrences for each mask in the backward pass.\n ```cpp\n if (isSubMask(A[i], mask)) cnt[mask]++;\n ```\n\n- **Update `suf` Array**:\n - Store the index `i` as the last index for the mask if it hasn\'t been set yet.\n ```cpp\n if (dp[mask] <= k && cnt[mask] >= k && suf[mask] == -1) {\n suf[mask] = i;\n }\n ```\n\n#### 4. **Finding the Maximum Value**\n\n- **Iterate Over Possible Masks**:\n - Compute the XOR value for each combination of `l` and `r`, where `r = mask ^ l`.\n ```cpp\n for (int mask = 127; mask >= 0; --mask) {\n for (int l = 127; l >= 0; --l) {\n int r = mask ^ l;\n if (pre[l] == -1 || suf[r] == -1) continue;\n if (pre[l] < suf[r]) {\n return mask;\n }\n }\n }\n ```\n\n- **Return Result**:\n - The maximum value found during the iteration is returned.\n\n### Code\n``` C++ []\nbool isSubMask(int a,int b){\n return (a | b) == b;\n}\nclass Solution {\npublic:\n int maxValue(vector<int>& A, int k) {\n int n = A.size();\n vector<int> pre(130, -1), suf(130, -1);\n vector<int> dp(128, 1e9), cnt(128, 0);\n\n for(int i = 0; i < n; ++i){\n dp[A[i]] = 1;\n for(int mask = 0; mask < 128; ++mask){\n dp[mask | A[i]] = min(dp[mask | A[i]], 1 + dp[mask]);\n if(isSubMask(A[i], mask)) cnt[mask]++;\n }\n\n for(int mask = 0; mask < 128; ++mask){\n if(dp[mask] <= k && cnt[mask] >= k && pre[mask] == -1){\n pre[mask] = i;\n }\n }\n }\n\n dp.assign(128, 1e9); cnt.assign(128, 0);\n for(int i = n - 1; i >= 0; --i){\n dp[A[i]] = 1;\n for(int mask = 0; mask < 128; ++mask){\n dp[mask | A[i]] = min(dp[mask | A[i]], 1 + dp[mask]);\n if(isSubMask(A[i], mask)) cnt[mask]++;\n }\n\n for(int mask = 0; mask < 128; ++mask){\n if(dp[mask] <= k && cnt[mask] >= k && suf[mask] == -1){\n suf[mask] = i;\n }\n }\n }\n int ans = 0;\n for(int mask = 127; mask >= 0; --mask){\n for(int l = 127; l >= 0; --l){\n int r = mask ^ l;\n if(pre[l] == -1 || suf[r] == -1) continue;\n if(pre[l] < suf[r]){\n return mask;\n }\n }\n }\n return 0;\n\n }\n};\n\n```\n``` Python3 []\nclass Solution:\n def maxValue(self, nums: List[int], k: int) -> int:\n n = len(nums)\n \n def get_possible(a):\n t1 = {(0, 0)}\n d = defaultdict(lambda: -1)\n for i, x in enumerate(a):\n t2 = set()\n for taken, val in t1:\n if taken < k:\n t2.add((taken + 1, val | x))\n if taken + 1 == k and val | x not in d:\n d[val | x] = i + 1\n t1.update(t2)\n return d\n \n a = get_possible(nums)\n b = get_possible(nums[::-1])\n ans = -float(\'inf\')\n \n for v1, x in a.items():\n for v2, y in b.items():\n if x + y <= n:\n ans = max(ans, v1 ^ v2)\n \n return ans\n\n```\n``` Java []\nclass Solution {\n private static final int MAX = 128;\n\n public int maxValue(int[] nums, int k) {\n boolean[][] dp = new boolean[nums.length][MAX];\n \n boolean[][] isMet = new boolean[MAX][k + 1];\n List<int[]> valid = new ArrayList<>();\n valid.add(new int[]{0, 0});\n isMet[0][0] = true;\n\n for (int i = nums.length - 1; i >= 0; --i) {\n List<int[]> nextValid = new ArrayList<>();\n for (int[] tmp : valid) {\n nextValid.add(tmp);\n if (tmp[1] + 1 <= k && !isMet[tmp[0] | nums[i]][tmp[1] + 1]) {\n isMet[tmp[0] | nums[i]][tmp[1] + 1] = true;\n nextValid.add(new int[]{tmp[0] | nums[i], tmp[1] + 1});\n }\n if (tmp[1] + 1 == k) {\n dp[i][tmp[0] | nums[i]] = true;\n }\n if (tmp[1] == k) {\n dp[i][tmp[0]] = true;\n }\n }\n valid = nextValid;\n }\n\n int result = 0;\n \n boolean[] isLeftMet = new boolean[MAX];\n isMet = new boolean[MAX][k + 1];\n valid = new ArrayList<>();\n valid.add(new int[]{0, 0});\n isMet[0][0] = true;\n\n for (int i = 0; i < nums.length; ++i) {\n List<int[]> nextValid = new ArrayList<>();\n for (int[] tmp : valid) {\n nextValid.add(tmp);\n if (tmp[1] + 1 <= k && !isMet[tmp[0] | nums[i]][tmp[1] + 1]) {\n isMet[tmp[0] | nums[i]][tmp[1] + 1] = true;\n nextValid.add(new int[]{tmp[0] | nums[i], tmp[1] + 1});\n }\n if (tmp[1] + 1 == k && !isLeftMet[tmp[0] | nums[i]] && i + 1 < nums.length) {\n int orResult = tmp[0] | nums[i];\n isLeftMet[orResult] = true;\n for (int j = 1; j < MAX; ++j) {\n if (dp[i + 1][j]) {\n result = Math.max(result, orResult ^ j);\n }\n }\n }\n }\n valid = nextValid;\n }\n \n return result;\n }\n}\n\n```\n### Conclusion\n\nThe approach efficiently computes the maximum sequence value by combining dynamic programming and bit manipulation. It tracks valid subsequences using bitmasks and updates the DP table to find the optimal subsequence values that satisfy the problem constraints.
9
3
['Dynamic Programming', 'C++', 'Java', 'Python3']
5
find-the-maximum-sequence-value-of-array
Beginner Level || Memoised solution || take , notake
beginner-level-memoised-solution-take-no-wp56
Intuition\n\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Tim
Great_Ali
NORMAL
2024-09-24T15:25:40.627196+00:00
2024-09-24T15:27:03.603711+00:00
281
false
# Intuition\n\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n- O(n*k*129 + n*129*129)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n- O(n*k*129)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n bool solve(int i, int len, int aur, vector<int>&nums,int k, vector<vector<vector<int>>>&dp){\n if(i>=nums.size()) return len == k ;\n if(dp[i][len][aur]!=-1) return dp[i][len][aur];\n bool take = 0 , notake = 0 ;\n if(len < k) take = solve(i+1,len+1,aur|nums[i],nums,k,dp);\n notake = solve(i+1,len,aur,nums,k,dp);\n return dp[i][len][aur] = take || notake ;\n }\n int maxValue(vector<int>& nums, int k) {\n int n = nums.size();\n vector<vector<vector<int>>>dp1(n+1,vector<vector<int>>(k+1,vector<int>(129,-1)));\n vector<vector<vector<int>>>dp2(n+1,vector<vector<int>>(k+1,vector<int>(129,-1)));\n solve(0,0,0,nums,k,dp1);\n reverse(nums.begin(),nums.end());\n solve(0,0,0,nums,k,dp2);\n int ans = 0 ;\n for(int i = k; i<=n-k; i++){\n for(int or1 = 0 ; or1<128; or1++){\n for(int or2 = 0 ; or2<128; or2++){\n if(dp1[i][k][or1]==-1 || dp2[n-i][k][or2] == -1 ) continue;\n if(dp1[i][k][or1] && dp2[n-i][k][or2])\n ans = max(ans, or1^or2);\n }\n }\n }\n return ans;\n }\n};\n```
6
0
['Dynamic Programming', 'Memoization', 'C++']
1
find-the-maximum-sequence-value-of-array
Video Explanation (Dissecting problem step by step with Intuition) [Why not recursion?]
video-explanation-dissecting-problem-ste-sea2
Explanation\n\nClick here for the video\n\n# Code\ncpp []\n#define pii pair<int, int>\n#define F first\n#define S second\n\nvector<vector<pii>> prefix(401, vect
codingmohan
NORMAL
2024-09-15T13:34:51.847579+00:00
2024-09-15T13:34:51.847609+00:00
430
false
# Explanation\n\n[Click here for the video](https://youtu.be/ea9Kjfc9ZzI)\n\n# Code\n```cpp []\n#define pii pair<int, int>\n#define F first\n#define S second\n\nvector<vector<pii>> prefix(401, vector<pii>(128, {1e9, 0}));\nvector<vector<pii>> suffix(401, vector<pii>(128, {1e9, 0}));\n\nclass Solution {\n \n void Compute (const vector<int>& arr) {\n int n = arr.size();\n \n prefix[0][arr[0]] = {1, 1};\n for (int j = 1; j < n; j ++) {\n prefix[j] = prefix[j-1];\n prefix[j][arr[j]].F = 1;\n prefix[j][arr[j]].S = max(prefix[j][arr[j]].S, 1);\n \n for (int val = 1; val < 128; val ++) {\n if (prefix[j-1][val].F == 1e9) continue;\n \n int new_val = val | arr[j];\n prefix[j][new_val].F = min(prefix[j][new_val].F, 1 + prefix[j-1][val].F);\n prefix[j][new_val].S = max(prefix[j][new_val].S, 1 + prefix[j-1][val].S);\n }\n }\n \n suffix[n-1][arr[n-1]] = {1, 1};\n for (int j = n-2; j >= 0; j --) {\n suffix[j] = suffix[j+1];\n suffix[j][arr[j]].F = 1;\n suffix[j][arr[j]].S = max(suffix[j][arr[j]].S, 1);\n \n for (int val = 1; val < 128; val ++) {\n if (suffix[j+1][val].F == 1e9) continue;\n \n int new_val = val | arr[j];\n suffix[j][new_val].F = min(suffix[j][new_val].F, 1 + suffix[j+1][val].F);\n suffix[j][new_val].S = max(suffix[j][new_val].S, 1 + suffix[j+1][val].S);\n }\n }\n }\n \n bool IsPossible (int lft_or, int rgt_or, int k, int n) {\n for (int l = 0; l < n-1; l ++) {\n pii lft = prefix[l][lft_or];\n pii rgt = suffix[l+1][rgt_or];\n \n if ((lft.F <= k && k <= lft.S) && (rgt.F <= k && k <= rgt.S)) return true;\n }\n return false;\n }\n \npublic:\n int maxValue(vector<int>& nums, int k) {\n prefix.clear(), suffix.clear();\n prefix.resize(401, vector<pii>(128, {1e9, 0}));\n suffix.resize(401, vector<pii>(128, {1e9, 0}));\n \n Compute (nums);\n int n = nums.size();\n \n int ans = 0;\n for (int l = 1; l < 128; l ++) {\n for (int r = 1; r < 128; r ++)\n if (IsPossible (l, r, k, n)) {\n // cout << l << " " << r << endl;\n ans = max (ans, l^r);\n }\n }\n return ans;\n }\n};\n```
6
0
['C++']
1
find-the-maximum-sequence-value-of-array
⚡ 2DP Solution and Explanation: Finding Maximum Sequence Value of Array
2dp-solution-and-explanation-finding-max-n5vw
Intuition\n Describe your first thoughts on how to solve this problem. \nThis problem can approached using dynamic programming (DP). The key is to break down t
subhanjan33
NORMAL
2024-09-14T16:10:11.674633+00:00
2024-09-14T16:10:11.674656+00:00
629
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThis problem can approached using dynamic programming (DP). The key is to break down the problem into smaller subproblems where we calculate the possible OR values of subsets up to a certain size for both the beginning and ending segments of the array. Just like in electrical courses!\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nUsing two dynamic programming tables (`dp1` and `dp2`) :\n - `dp1[i][j]` represents the set of possible OR values using exactly `j` elements from the subarray `nums[0..i-1]` \n - `dp2[i][j]` represents the set of possible OR values using exactly `j` elements from the subarray `nums[i..n-1]`.\n\n1. **Initialization**:\n - `dp1[0][0]` is initialized with `{0}` because OR of zero elements is 0.\n - Similarly, `dp2[n][0]` is initialized to `{0}`.\n\n2. **Filling `dp1`**:\n - Iterate over each element `num` in `nums` from left to right.\n - For each count `cnt` from 0 to `k-1`, update `dp1[i][cnt+1]` by taking OR with the current number `num` for all values in `dp1[i][cnt]`.\n\n3. **Filling `dp2`**:\n - Iterate over each element `num` in `nums` from right to left.\n - For each count `cnt` from 0 to `k-1`, update `dp2[i][cnt+1]` by taking OR with the current number `num` for all values in `dp2[i+1][cnt]`.\n\n4. **Combining Results**:\n - For each split position `i`, consider the maximum XOR of all combinations of values from `dp1[i][k]` and `dp2[i][k]`.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nThe time complexity is $$O(n \\cdot k \\cdot 2^k)$$, where `n` is the length of the input array and `k` is the maximum number of elements to consider. This comes from the fact that in the worst case, for each element and for each possible subset size up to `k`, we might be dealing with up to `2^k` possible OR results due to combinatorial effects.\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nThe space complexity is also $$O(n \\cdot 2^k)$$ due to storing OR results for up to `k` elements across `n` positions in both `dp1` and `dp2`.\n\n# Code\n```python3 []\nclass Solution:\n def maxValue(self, nums: List[int], k: int) -> int:\n n = len(nums)\n # dp1[i][j] = set of OR values using j elements from nums[0..i]\n dp1 = [dict() for _ in range(n + 1)]\n dp1[0][0] = {0}\n for i in range(n):\n dp1[i + 1] = {key: set(val) for key, val in dp1[i].items()}\n num = nums[i]\n for cnt in range(k):\n if cnt in dp1[i] and cnt + 1 <= k:\n for val in dp1[i][cnt]:\n new_or = val | num\n dp1[i + 1].setdefault(cnt + 1, set()).add(new_or)\n # dp2[i][j] = set of OR values using j elements from nums[i..n]\n dp2 = [dict() for _ in range(n + 1)]\n dp2[n][0] = {0}\n for i in range(n - 1, -1, -1):\n dp2[i] = {key: set(val) for key, val in dp2[i + 1].items()}\n num = nums[i]\n for cnt in range(k):\n if cnt in dp2[i + 1] and cnt + 1 <= k:\n for val in dp2[i + 1][cnt]:\n new_or = val | num\n dp2[i].setdefault(cnt + 1, set()).add(new_or)\n max_value = 0\n #combine dp1, dp2 at each split position\n for i in range(n + 1):\n if k in dp1[i] and k in dp2[i]:\n for val1 in dp1[i][k]:\n for val2 in dp2[i][k]:\n max_value = max(max_value, val1 ^ val2)\n return max_value\n\n```
6
0
['Dynamic Programming', 'Python3']
0
find-the-maximum-sequence-value-of-array
Most Detailed Approach with Intution - 4D DP to 3D dp
most-detailed-approach-with-intution-4d-qtobh
Intuition\n\n# Why greedy donot work?\nWhat we can think in case of greedy , to maximize the bit by bit of the number starting from the most significant bit to
karMa_108
NORMAL
2024-09-15T10:52:53.182424+00:00
2024-09-15T10:52:53.182449+00:00
260
false
# Intuition\n\n# Why greedy donot work?\nWhat we can think in case of greedy , to maximize the bit by bit of the number starting from the most significant bit to least significant bit , but how we can handle it as we move in further selecting the next subsequence elements , as XOR property we also know , it makes similar bit equal to 0 , it can be worst solution for us also if more bits are 1. \n\nSo now we can move to one solution try every possible and try to get the maximum XOR out of it , so it goes to dynamic programming only.\n\n# Approach\nLets start with what we need , so my first thought should be what things I need to be present in my state, what parameters are going to change.\nIts the index(i), cnt(elements picked in subsequences), OR1(OR of first k elements), OR2(OR of last K elements)\n\n`dp[i][cnt][or1][or2] = 1 => What it means that till ith index , we picked the cnt no of elements and for which the bitwise OR of the first subsequence is or1 and second half subsequence is or2 `\n\n**Remember or of the any number of elements is always less than 128 because if you take or of any number of elements within 2^7 , its less than 128**\n\nwhat is its space - $$O(400* 400* 128*128)$$ ~ 1e9 which is out of bound\n\nSo we should reduce the number of states now , but i and cnt are neccesary states , so we should seperate or1 and or2 now, lets see.\n\n**Now**, what we do we make 2 dp arrays `dp1[i][cnt][or1]` and `dp2[i][cnt][or2]`\n=> dp1 tells us that from the start of the array till index i with cnt elements picked whether the OR of the elements as or1 is possible or not\n\n=> similiarly, dp2 tells us that from the end of the array till index i with cnt elements picked whether the OR of the elements as or1 is possible or not\n\nSo I make two 3d vector suffix and prefix , \n=> `prefix[i][k][or1]` stores whether it\'s possible to form a subsequence of length k that ends at index i in the original array with an OR value of or1\n\n=> `(suffix[n - i][k][or2])` similarly stores information for the reversed array, indicating possible subsequences that start at index n - i with an OR value of or2\n\n# Code Explanation - \n\n```\nint ans = 0;\n for (int i = k; i <= n - k; i++) {\n for (int or1 = 0; or1 < mx; or1++) {\n for (int or2 = 0; or2 < mx; or2++) {\n if (prefix[i][k][or1] && suffix[n - i][k][or2]) {\n ans = max(ans, or1 ^ or2);\n }\n }\n }\n }\n\n```\n\n`dp[0][0][0] = 1` - It means till 0th index , we picked 0 elements and its `OR` is 0 so it is true\n\nThe split point i represents the boundary between the prefix (which ends at index i - 1) and the suffix (which starts at index i)\n`Why Start at i = k`\nThe prefix must contain at least k elements. Starting the loop at i = k ensures that there are at least k elements in the prefix (indices 0 through i - 1)\n\n`Why End at i = n - k`\nThe suffix must also contain at least k elements. Ending the loop at i = n - k ensures that there are at least k elements in the suffix (indices i through n - 1)\n\nThe nested loops iterate over all possible OR values (or1 for prefix and or2 for suffix) from 0 to 127 (mx = 128).\n\n`prefix[i][k][or1]` is `1`, which means it\'s possible to form a subsequence of length `k` ending at index `i` with an OR value of `or1`\n\n`suffix[n - i][k][or2]` is `1`, meaning it\'s possible to form a subsequence of length `k` starting from index `n - i` (in the reversed array) with an OR value of `or2`\n\nIf both conditions are true, it calculates the XOR of `or1` and `or2` `(or1 ^ or2)`, then updates `ans` to store the maximum XOR value encountered so far\n\n```\nvector<vector<vector<int>>> f(vector<int> &nums, int k) {\n int n = nums.size();\n \n vector dp(n + 1, vector(k + 1, vector(mx + 1, 0)));\n \n dp[0][0][0] = 1;\n\n for (int i = 0; i < n; i++) {\n for (int x = 0; x <= k; x++) {\n for (int o = 0; o < mx; o++) {\n dp[i + 1][x][o] |= dp[i][x][o];\n \n if (x + 1 <= k) {\n dp[i + 1][x + 1][o | nums[i]] |= dp[i][x][o];\n }\n }\n }\n }\n \n vector<vector<vector<int>>> res(n + 1, vector(k + 1, vector(mx + 1, 0)));\n for (int i = 0; i <= n; i++) {\n for (int o = 0; o < mx; o++) {\n res[i][k][o] = dp[i][k][o];\n }\n }\n \n return res;\n }\n```\n\nIt is three nested loop which which iterates for every elements nums, with every possible number of elements less than `k`, with the or value present between `0` to `127`\n\n`dp[i + 1][x][o] |= dp[i][x][o]`\nThis line is the "not pick" case, `dp[i + 1][x][o]` is upadated to previous state of element , if till i elements `o` or is possible then till i+1 is also possible otherwise not.\n\n```\nif (x + 1 <= k){\n dp[i + 1][x + 1][o | nums[i]] |= dp[i][x][o];\n}\n```\n\nThis is the "pick" case, If it\'s valid to include the current element, the new OR value becomes `o | nums[i]`. This is a bitwise OR operation that combines the current OR value (o) with the element `nums[i]`\n\n`dp[i + 1][x + 1][o | nums[i]] |= dp[i][x][o]` sets the state to true if it\'s possible to pick x + 1 elements with the new OR value using the first i + 1 element\n# Complexity\n- Time complexity:\n$$O(n*k*128)$$\n=> n is the length of the input array nums\n=> k is the size of the subsequence\n=> 128 is the limit for the OR values since nums[i] is constrained to be less than 2^7\n\nI think now everything makes sense, I go to the depth till it is possible for me, pls give your reviews about it \n\n\n- Space complexity:\nThe space complexity here is $$O(n\xD7k\xD7128)$$ because of the 3D dp array storing results for each combination of index, count, and OR value\n\n# Code\n```cpp []\nclass Solution {\npublic:\n int mx = 128;\n\n vector<vector<vector<int>>> f(vector<int> &nums, int k) {\n int n = nums.size();\n \n vector dp(n + 1, vector(k + 1, vector(mx + 1, 0)));\n \n dp[0][0][0] = 1;\n\n for (int i = 0; i < n; i++) {\n for (int x = 0; x <= k; x++) {\n for (int o = 0; o < mx; o++) {\n dp[i + 1][x][o] |= dp[i][x][o];\n \n if (x + 1 <= k) {\n dp[i + 1][x + 1][o | nums[i]] |= dp[i][x][o];\n }\n }\n }\n }\n \n vector<vector<vector<int>>> res(n + 1, vector(k + 1, vector(mx + 1, 0)));\n for (int i = 0; i <= n; i++) {\n for (int o = 0; o < mx; o++) {\n res[i][k][o] = dp[i][k][o];\n }\n }\n \n return res;\n }\n\n int maxValue(vector<int>& nums, int k) {\n int n = nums.size();\n vector<int> nums_rev = nums;\n reverse(nums_rev.begin(), nums_rev.end());\n \n auto prefix = f(nums, k);\n auto suffix = f(nums_rev, k);\n \n int ans = 0;\n for (int i = k; i <= n - k; i++) {\n for (int or1 = 0; or1 < mx; or1++) {\n for (int or2 = 0; or2 < mx; or2++) {\n if (prefix[i][k][or1] && suffix[n - i][k][or2]) {\n ans = max(ans, or1 ^ or2);\n }\n }\n }\n }\n \n return ans;\n }\n};\n```
4
0
['Dynamic Programming', 'Greedy', 'Suffix Array', 'Prefix Sum', 'C++']
1
find-the-maximum-sequence-value-of-array
Forward + Backward DP in Python3
forward-backward-dp-in-python3-by-metaph-m6ht
Approach\n Describe your approach to solving the problem. \nThe number is up to $2^7$ only, so we can split the nums into the left and the right parts. At a piv
metaphysicalist
NORMAL
2024-09-14T17:48:23.553469+00:00
2024-09-14T17:48:23.553494+00:00
174
false
# Approach\n<!-- Describe your approach to solving the problem. -->\nThe number is up to $2^7$ only, so we can split the nums into the left and the right parts. At a pivot $i$, we would like to try each possible value $p$ that can be obtained by the OR operation for $k$ elements in `nums[:i+1]` and each possible value $q$ that can be obtained by the OR operation for $k$ elements in `nums[i:]`, and find the maximum $p \\oplus q$. \n\nTo do so, we need to precompute all the possible elements that can be obtained within `nums[:i+1]` and `nums[i:]`. So we perform forward and backward dynamic programming on `nums` for the precomutation. Finally, enumerate all the pivot $i$ to find the global maximum value as the answer. \n\n\n# Complexity\n- Time complexity: $O(NK)$ \n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $O(NK)$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```python3 []\nclass Solution:\n def maxValue(self, nums: List[int], k: int) -> int:\n n = len(nums)\n\n def dp(nums):\n dp = defaultdict(set)\n for i in range(n):\n for j in range(1, min(k, i+1)+1):\n dp[(i, j)] = dp[(i-1, j)].copy()\n if len(dp[(i-1, j-1)]) == 0:\n dp[(i, j)].add(nums[i])\n else:\n for v in dp[(i-1, j-1)]:\n dp[(i, j)].add(v | nums[i])\n return dp\n\n forward = dp(nums)\n backward = dp(nums[::-1])\n ans = 0\n for i in range(k-1, n - k):\n for p in forward[(i, k)]:\n for q in backward[(n - i - 2, k)]:\n ans = max(ans, p ^ q)\n return ans\n```
3
0
['Dynamic Programming', 'Python3']
1
find-the-maximum-sequence-value-of-array
Solution
solution-by-shree_govind_jee-r60s
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
Shree_Govind_Jee
NORMAL
2024-09-14T16:07:37.595830+00:00
2024-09-14T16:07:37.595857+00:00
263
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\n public:\n int maxValue(vector<int>& a, int z) {\n int n = (int) a.size();\n vector dp0(n + 1, vector(z + 1, vector<bool>(1 << 7)));\n dp0[0][0][0] = true;\n for (int i = 0; i < n; i++) {\n dp0[i + 1] = dp0[i];\n for (int j = 0; j < z; j++) {\n for (int k = 0; k < (1 << 7); k++) {\n if (dp0[i][j][k]) {\n dp0[i + 1][j + 1][k | a[i]] = true;\n }\n }\n }\n }\n vector dp1(n + 1, vector(z + 1, vector<bool>(1 << 7)));\n dp1[n][0][0] = true;\n for (int i = n - 1; i >= 0; i--) {\n dp1[i] = dp1[i + 1];\n for (int j = 0; j < z; j++) {\n for (int k = 0; k < (1 << 7); k++) {\n if (dp1[i + 1][j][k]) {\n dp1[i][j + 1][k | a[i]] = true;\n }\n }\n }\n }\n int ans = 0;\n for (int i = 0; i <= n; i++) {\n for (int p = 0; p < (1 << 7); p++) {\n for (int q = 0; q < (1 << 7); q++) {\n if (dp0[i][z][p] && dp1[i][z][q]) {\n ans = max(ans, p ^ q);\n }\n }\n }\n }\n return ans;\n }\n};\n```
3
0
['C++']
1
find-the-maximum-sequence-value-of-array
2 DP solution, beats 100%
2-dp-solution-beats-100-by-rashmeetnayya-hcko
\n\n# Code\npython3 []\nclass Solution:\n def maxValue(self, nums: List[int], k: int) -> int:\n self.nums = nums\n n, ans = len(nums), 0\n
rashmeetnayyar
NORMAL
2024-09-15T20:45:51.971030+00:00
2024-09-15T20:45:51.971047+00:00
239
false
\n\n# Code\n```python3 []\nclass Solution:\n def maxValue(self, nums: List[int], k: int) -> int:\n self.nums = nums\n n, ans = len(nums), 0\n for i in range(1, n+1):\n for val1 in self.dp1(i, k):\n for val2 in self.dp2(i,k):\n ans = max(val1^val2, ans)\n # for j in range(k):\n # del self.dp1(i-2, j)\n \n return ans\n\n @lru_cache(maxsize=2000)\n def dp1(self, n, k):\n\n # base condition\n if n<k:\n # print(f"self.dp1({n}, {k})= []")\n return set()\n \n if k==1:\n # print(f"self.dp1({n}, {k})= {set(self.nums[:n])}")\n\n return set(self.nums[:n])\n\n ans = set()\n for val in self.dp1(n-1, k-1):\n ans.add(val | self.nums[n-1])\n for val in self.dp1(n-1, k):\n ans.add(val)\n # print(f"self.dp1({n}, {k})={ans}")\n \n return ans\n\n @lru_cache(maxsize=2000)\n def dp2(self, m, k):\n # base condition\n n = len(self.nums)\n if k> n- m:\n # print(f"self.dp2({m}, {k})= []")\n return set()\n \n if k==1:\n # print(f"self.dp2({m}, {k})= {set(self.nums[m:])}")\n return set(self.nums[m:])\n\n ans = set()\n\n for val in self.dp2(m+1, k-1):\n ans.add(val | self.nums[m])\n for val in self.dp2(m+1, k):\n ans.add(val)\n # print(f"self.dp2({m}, {k})={ans}")\n \n return ans\n\n```
2
0
['Python3']
0
find-the-maximum-sequence-value-of-array
DP || C++ || max sequence value .
dp-c-max-sequence-value-by-rishiinsane-qtei
IntuitionThe problem requires selecting k elements from an array nums in two non-overlapping groups (one from left to right and one from right to left) to maxim
RishiINSANE
NORMAL
2025-01-31T17:06:37.887657+00:00
2025-01-31T17:06:37.887657+00:00
14
false
# Intuition The problem requires selecting k elements from an array nums in two non-overlapping groups (one from left to right and one from right to left) to maximize the XOR of their respective bitwise OR results. The key observation is that the OR operation accumulates bits, and maximizing XOR means finding two groups with the most different set bits. Thus, we track possible OR values for every subset of k elements in the left and right halves of the array and determine the best XOR between them. # Approach The solution uses DFS with memoization to efficiently explore all possible k-element subsets. The function d1 processes subsets from left to right, storing the minimum index where a particular OR value can be achieved in exists1. Similarly, d2 explores right to left, storing the maximum index in exists2. The condition exists1[i] < exists2[j] ensures non-overlapping subsets. The final XOR maximization is done via a nested loop over 128 possible OR values. The solution runs in O(n * k * 128²) with O(n * 128²) space due to DP memoization. # Complexity - Time complexity: O(n × k × 128 + 128²) ≈ O(n × k × 128) - Space complexity: O(n × k × 128) # Code ```cpp [] class Solution { public: bool dp1[401][201][128] = {}, dp2[401][201][128] = {}; int maxValue(vector<int>& nums, int k) { vector<int> exists1(128,INT_MAX),exists2(128,INT_MIN); d1(0,k,0,nums,exists1,k); d2(nums.size()-1,k,0,nums,exists2,k); int ans=0; for(int i=0;i<128;i++) { for(int j=0;j<128;j++) { if(exists1[i] < exists2[j]) ans = max(ans,i^j); } } return ans; } void d1(int ind, int req, int or1, vector<int>& nums,vector<int>& exists1, int k) { if(req==0) exists1[or1] = min(exists1[or1],ind-1); else if(ind+k<nums.size() && !dp1[ind][req][or1]) { dp1[ind][req][or1] = true; d1(ind+1,req,or1,nums,exists1,k); d1(ind+1,req-1,or1|nums[ind],nums,exists1,k); } } void d2(int ind, int req, int or2, vector<int>& nums,vector<int>& exists2, int k) { if(req==0) exists2[or2] = max(exists2[or2],ind+1); else if(ind >= k && !dp2[ind][req][or2]) { dp2[ind][req][or2] = true; d2(ind-1,req,or2,nums,exists2,k); d2(ind-1,req-1,or2|nums[ind],nums,exists2,k); } } }; ```
1
0
['C++']
0
find-the-maximum-sequence-value-of-array
Rolling DP + Bitsets for Maximum XOR of OR-Segments (C++)
rolling-dp-bitsets-for-maximum-xor-of-or-0zi2
IntuitionWe want to select a subsequence of size 2 × k to maximize (OR of first k) ⊕ (OR of second k). A brute force approach is infeasible for large n. Instead
4fPYADGrHM
NORMAL
2025-01-04T14:25:49.003907+00:00
2025-01-04T14:25:49.003907+00:00
23
false
## Intuition We want to select a subsequence of size 2 × k to maximize (OR of first k) ⊕ (OR of second k). A brute force approach is infeasible for large n. Instead, we use dynamic programming with bitsets: 1. Compute the maximum OR of all elements. This defines an upper bound on OR-values. 2. From the left, keep track of which OR-values are possible for picking exactly \(j\) items from the first \(i\) elements. Repeat similarly from the right. 3. Combine left and right possibilities to find the maximum XOR of all OR-pairs that arise from splitting the array into two blocks of size \(k\). ## Approach 1. Calculate `maxOR` as the bitwise OR of every element in `nums`. 2. Use rolling DP arrays to track possible OR-values for picking `j` items up to index `i` (from the left) while storing only the final bitset for `j = k`. 3. Do the same from the right, storing possible OR-values for picking `k` items in `nums[i..n-1]`. 4. To combine, iterate over feasible split points where the left portion picks `k` items and the right portion picks `k` items. Enumerate all OR-values from each side and compute their XOR. Keep track of the maximum. ## Complexity - **Time Complexity**: - Let n be the length of `nums`, and let `m = maxOR`. - The rolling DP from the left and from the right each require O(n × k × m) in the worst case. Combining the bitsets for XOR can add up to O(n × m × m), but typically is reduced by sparse population in the bitset. - For moderate `m` (e.g., up to 130 as in the example), this is efficient. - **Space Complexity**: - We keep two rolling DP arrays of size O(k × m) and two arrays of bitsets of size O(n × m), so the total is O(n × m + k × m). --- ## Code ```cpp #include <bits/stdc++.h> using namespace std; class Solution { public: int maxValue(vector<int>& nums, int k) { int n = (int) nums.size(); if (2 * k > n) return 0; // Safety check // 1) Compute overall maxOR int maxOR = 0; for (int x : nums) { maxOR |= x; } // We'll store possible ORs in a bitset of size (maxOR + 1) // leftOR[i] = bitset of all OR-values achievable by picking exactly k elements in nums[0..i-1] // rightOR[i] = bitset of all OR-values achievable by picking exactly k elements in nums[i..n-1] vector< bitset<131> > leftOR(n + 1), rightOR(n + 1); // ------------------------- // 2) Rolling DP from the Left // dp[j]: a bitset tracking all OR-values if we pick j elements from the first i elements processed vector< bitset<131> > curr(k + 1), prev(k + 1); // Initialize dp for i=0 prev[0].set(0); // picking 0 elements => OR=0 for (int j = 1; j <= k; j++) { prev[j].reset(); // picking >0 elements from empty array is impossible } for (int i = 1; i <= n; i++) { int val = nums[i - 1]; // copy prev -> curr for (int j = 0; j <= k; j++) { curr[j] = prev[j]; } // pick current element for (int j = 1; j <= k; j++) { // for each OR-value in prev[j-1], set OR-value|(val) in curr[j] auto &src = prev[j - 1]; for (int v = src._Find_first(); v <= maxOR; v = src._Find_next(v)) { curr[j].set(v | val); if (v == (maxOR)) break; } } // move curr -> prev for (int j = 0; j <= k; j++) { prev[j] = curr[j]; } // store the k-element bitset for boundary i leftOR[i] = prev[k]; } // ------------------------- // 3) Rolling DP from the Right // We'll do dp2 similarly but from the end for (int j = 0; j <= k; j++) { prev[j].reset(); } prev[0].set(0); for (int i = n - 1; i >= 0; i--) { int val = nums[i]; // copy prev -> curr for (int j = 0; j <= k; j++) { curr[j] = prev[j]; } // pick current element for (int j = 1; j <= k; j++) { auto &src = prev[j - 1]; for (int v = src._Find_first(); v <= maxOR; v = src._Find_next(v)) { curr[j].set(v | val); if (v == maxOR) break; } } // move curr -> prev for (int j = 0; j <= k; j++) { prev[j] = curr[j]; } // store the k-element bitset for boundary i rightOR[i] = prev[k]; } // ------------------------- // 4) Combine int ans = 0; // We consider splitting at i, meaning the left group picks k items from [0..i-1], // and the right group picks k items from [i..n-1]. for (int i = k; i <= n - k; i++) { auto &L = leftOR[i]; // possible ORs from picking k in the left auto &R = rightOR[i]; // possible ORs from picking k in the right // pairwise XOR // collect set bits in L vector<int> leftVals; for (int v = L._Find_first(); v <= maxOR; v = L._Find_next(v)) { leftVals.push_back(v); if (v == maxOR) break; } // now check R for (int v = R._Find_first(); v <= maxOR; v = R._Find_next(v)) { for (int p: leftVals) { ans = max(ans, p ^ v); } if (v == maxOR) break; } } return ans; } }; ```
1
0
['Array', 'Dynamic Programming', 'Bit Manipulation', 'C++']
0
find-the-maximum-sequence-value-of-array
Easiest Explanation
easiest-explanation-by-kartikeysemwal-myfv
Intuition\n Describe your first thoughts on how to solve this problem. \nMake sure you understand the OR operation trick. As the OR operation just adds 0 or mor
kartikeysemwal
NORMAL
2024-09-26T17:50:55.651855+00:00
2024-09-26T17:50:55.651885+00:00
42
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nMake sure you understand the OR operation trick. As the OR operation just adds 0 or more bits (cannot remove), the unique numbers generated will always be less.\nTaking this idea further, first we can find out from left to right ORs of number to a particular index and only store the ORs of K numbers at that index.\nThen while doing from right to left we can find out the answer.\n\n# Code\n```java []\nclass Solution {\n public int maxValue(int[] nums, int k) {\n // find all or upto index\n\n int n = nums.length;\n\n HashMap<Integer, HashSet<Integer>> leftMap = new HashMap<>();\n\n for(int i=1; i<=k; i++)\n {\n leftMap.put(i, new HashSet<>());\n }\n\n HashMap<Integer, HashSet<Integer>> valsAtIndex = new HashMap<>();\n\n for(int i=0; i<n-k; i++)\n {\n int cur = nums[i];\n for(int j=k-1; j>=1; j--)\n {\n for(int x: leftMap.get(j))\n {\n leftMap.get(j + 1).add(x | cur);\n }\n }\n\n leftMap.get(1).add(cur);\n\n valsAtIndex.put(i, new HashSet<>(leftMap.get(k)));\n }\n\n int ans = 0;\n\n HashMap<Integer, HashSet<Integer>> rightMap = new HashMap<>();\n for(int i=1; i<=k; i++)\n {\n rightMap.put(i, new HashSet<>());\n }\n\n for(int i=n-1; i>=k; i--)\n {\n int cur = nums[i];\n for(int j=k-1; j>=1; j--)\n {\n for(int x: rightMap.get(j))\n {\n rightMap.get(j + 1).add(x | cur);\n }\n }\n\n rightMap.get(1).add(cur);\n\n if(n - i < k)\n {\n continue;\n }\n\n for(int x: valsAtIndex.get(i-1))\n {\n for(int y: rightMap.get(k))\n {\n ans = Math.max(ans, x ^ y);\n }\n }\n }\n\n return ans;\n }\n}\n```
1
0
['Java']
0
find-the-maximum-sequence-value-of-array
java dp
java-dp-by-mot882000-8vj3
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
mot882000
NORMAL
2024-09-14T16:31:21.995124+00:00
2024-09-14T16:31:21.995160+00:00
222
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```java []\nclass Solution {\n public int maxValue(int[] nums, int k) {\n \n int n = nums.length;\n boolean dp[][][] = new boolean[n][k+2][1 << 7+1];\n\n dp[0][1][nums[0]] = true;\n \n for(int i = 1; i < n; i++) {\n dp[i][1][nums[i]] = true;\n for(int j = 1; j <= 128; j++) {\n for(int a = 1; a <= k; a++) {\n if ( dp[i-1][a][j] ) {\n dp[i][a+1][j|nums[i]] = true;\n dp[i][a][j] = true;\n }\n }\n }\n }\n\n\n boolean dp2[][][] = new boolean[n][k+2][1 << 7+1];\n dp2[n-1][1][nums[n-1]] = true;\n \n for(int i = n-2; i >= 0; i--) {\n dp2[i][1][nums[i]] = true;\n for(int j = 1; j <= 128; j++) {\n for(int a = 1; a <= k; a++) {\n if ( dp2[i+1][a][j]) {\n dp2[i][a+1][j|nums[i]] = true;\n dp2[i][a][j] = true;\n }\n }\n }\n }\n\n int max = 0;\n for(int i = 0; i < n; i++) {\n if ( i+1 >= k && n-(i+1) >= k) {\n for(int a = 1; a <= 128; a++) {\n for(int b = 1; b <= 128; b++) {\n if ( dp[i][k][a] && dp2[i+1][k][b] ) {\n // System.out.println(i + " " + a + " " + (i+1) + " " + b);\n max = Math.max(max, a^b);\n }\n \n }\n }\n }\n }\n\n \n return max;\n }\n}\n```
1
0
['Dynamic Programming', 'Java']
0
find-the-maximum-sequence-value-of-array
[C++] Dp from front | Dp back | Iterate over all possible values | Easy to understand
c-dp-from-front-dp-back-iterate-over-all-2c60
\n\n# Code\ncpp []\nclass Solution {\npublic:\n int n;\n int maxValue(vector<int>& a, int k) {\n n = (int)a.size();\n vector<vector<vector<i
braindroid
NORMAL
2024-09-14T16:10:34.580698+00:00
2024-09-14T16:10:34.580726+00:00
617
false
\n\n# Code\n```cpp []\nclass Solution {\npublic:\n int n;\n int maxValue(vector<int>& a, int k) {\n n = (int)a.size();\n vector<vector<vector<int>>>dp(n+2,vector<vector<int>>(k+2,vector<int>(262,0)));\n vector<vector<vector<int>>>dp1(n+2,vector<vector<int>>(k+2,vector<int>(262,0)));\n n = (int)a.size();\n dp[0][0][0] = 1;\n unordered_map<int,int>mp;\n for(int i = 0 ; i < n ; i++) {\n for(int j = 0 ; j < k ; j++) {\n for(int OR = 0 ; OR <= 260 ; OR++) {\n // if i include this element , then.\n if(dp[i][j][OR]) {\n dp[i+1][j+1][OR|a[i]] = 1;\n }\n // dont include this element.\n dp[i+1][j][OR] |= dp[i][j][OR];\n }\n }\n }\n for(int i = 0 ; i <= n ; i++) {\n for(int OR = 0 ; OR <= 260 ; OR++) {\n if(dp[i][k][OR]) {\n if(mp.find(OR) == mp.end()) {\n mp[OR] = i;\n }\n }\n }\n }\n reverse(a.begin(),a.end());\n dp1[0][0][0] = 1;\n for(int i = 0 ; i < n ; i++) {\n for(int j = 0 ; j < k ; j++) {\n for(int OR = 0 ; OR <= 260 ; OR++) {\n // if i include this element , then.\n if(dp1[i][j][OR]) {\n dp1[i+1][j+1][OR|a[i]] = 1;\n }\n // dont include this element.\n dp1[i+1][j][OR] |= dp1[i][j][OR];\n }\n }\n }\n unordered_map<int,int>mp1;\n for(int i = 0 ; i <= n ; i++) {\n for(int OR = 0 ; OR <= 260 ; OR++) {\n if(dp1[i][k][OR]) {\n if(mp1.find(OR) == mp1.end()) {\n mp1[OR] = n-i;\n }\n }\n }\n }\n int ans = 0;\n for(int i = 0 ; i <= 260 ; i++) {\n for(int j = 0 ; j <= 260 ; j++) {\n if(mp.find(i) != mp.end() && mp1.find(j) != mp.end()) {\n int st = mp[i];\n int en = mp1[j];\n if(st <= en) {\n ans = max(ans,(i^j));\n }\n }\n }\n }\n return ans;\n }\n};\n```
1
0
['C++']
1
find-the-maximum-sequence-value-of-array
soln
soln-by-shikharcookies-m885
\n# Code\njava []\nclass Solution {\n private static final int max = 128;\n\n public int maxValue(int[] nums, int k) {\n boolean[][] dp = new boole
shikharcookies
NORMAL
2024-09-14T16:03:56.928216+00:00
2024-09-14T16:10:30.030432+00:00
162
false
\n# Code\n```java []\nclass Solution {\n private static final int max = 128;\n\n public int maxValue(int[] nums, int k) {\n boolean[][] dp = new boolean[nums.length][max];\n {\n boolean[][] isMet = new boolean[max][k + 1];\n List<int[]> valid = new ArrayList<>();\n valid.add(new int[]{0, 0});\n isMet[0][0] = true;\n\n for (int i = nums.length - 1; i >= 0; --i) {\n List<int[]> nextValid = new ArrayList<>();\n for (int[] tmp : valid) {\n nextValid.add(tmp);\n if (tmp[1] + 1 <= k && !isMet[tmp[0] | nums[i]][tmp[1] + 1]) {\n isMet[tmp[0] | nums[i]][tmp[1] + 1] = true;\n nextValid.add(new int[]{tmp[0] | nums[i], tmp[1] + 1});\n }\n if (tmp[1] + 1 == k) {\n dp[i][tmp[0] | nums[i]] = true;\n }\n if (tmp[1] == k) {\n dp[i][tmp[0]] = true;\n }\n }\n valid = nextValid;\n }\n }\n\n int res = 0;\n {\n boolean[] isLeftMet = new boolean[max];\n boolean[][] isMet = new boolean[max][k + 1];\n List<int[]> valid = new ArrayList<>();\n valid.add(new int[]{0, 0});\n isMet[0][0] = true;\n\n for (int i = 0; i < nums.length; ++i) {\n List<int[]> nextValid = new ArrayList<>();\n for (int[] tmp : valid) {\n nextValid.add(tmp);\n if (tmp[1] + 1 <= k && !isMet[tmp[0] | nums[i]][tmp[1] + 1]) {\n isMet[tmp[0] | nums[i]][tmp[1] + 1] = true;\n nextValid.add(new int[]{tmp[0] | nums[i], tmp[1] + 1});\n }\n if (tmp[1] + 1 == k && !isLeftMet[tmp[0] | nums[i]] && i + 1 < nums.length) {\n int orResult = tmp[0] | nums[i];\n isLeftMet[orResult] = true;\n for (int j = 1; j < max; ++j) {\n if (dp[i + 1][j]) {\n res = Math.max(res, orResult ^ j);\n }\n }\n }\n }\n valid = nextValid;\n }\n }\n return res;\n }\n}\n```
1
0
['Java']
0
find-the-maximum-sequence-value-of-array
Beat 100% || Easy and Simple Approach
beat-100-easy-and-simple-approach-by-jai-zjx1
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
jainarpan02
NORMAL
2024-09-14T16:03:52.806722+00:00
2024-09-14T16:03:52.806755+00:00
440
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\n vector<vector<vector<int>>> func(vector<int>& nums, int k) {\n int n = nums.size();\n vector<vector<vector<int>>> dp(\n n, vector<vector<int>>(k + 1, vector<int>(129)));\n dp[0][1][nums[0]] = 1;\n dp[0][0][0] = 1;\n\n for (int i = 1; i < n; i++) {\n dp[i][0][0] = 1;\n for (int j = 1; j <= k; j++) {\n for (int x = 0; x <= 128; x++) {\n if (!dp[i][j][x])\n dp[i][j][x] = dp[i - 1][j][x];\n int next = nums[i] | x;\n if (dp[i - 1][j - 1][x])\n dp[i][j][next] = dp[i - 1][j - 1][x];\n }\n }\n }\n return dp;\n }\n\npublic:\n int maxValue(vector<int>& nums, int k) {\n vector<vector<vector<int>>> left = func(nums, k);\n reverse(begin(nums), end(nums));\n vector<vector<vector<int>>> right = func(nums, k);\n reverse(begin(right), end(right));\n int n = nums.size();\n int res = 0;\n for (int i = k - 1; i + k < nums.size(); i++) {\n for (int a = 0; a <= 128; a++) {\n for (int b = 0; b <= 128; b++) {\n if (left[i][k][a] && right[i + 1][k][b]) {\n res = max(res, a ^ b);\n }\n }\n }\n }\n return res;\n }\n};\n```
1
0
['C++']
0
find-the-maximum-sequence-value-of-array
◈ Python ◈ DP ◈ Math
python-dp-math-by-zurcalled_suruat-zlf1
Glossary: nums: The input array of non-negative integers. k: The maximum number of elements that can be selected from nums to form a subsequence. N: The length
zurcalled_suruat
NORMAL
2025-02-13T18:05:51.484280+00:00
2025-02-13T18:05:51.484280+00:00
6
false
Glossary: - $nums$: The input array of non-negative integers. - $k$: The maximum number of elements that can be selected from $nums$ to form a subsequence. - $N$: The length of the input array $nums$. - $ix_k$: Index of the $k$-th element in a subsequence. - $ix_{k+1}$: Index of the $(k+1)$-th element in a subsequence. - $dp[ix_k]$: A set storing all possible values of $left\_or(ix_k)$. - $left\_or(ix_k)$: The bitwise OR of the first $k$ elements of the subsequence up to the element at index $ix_k$. - $right\_or(ix_{k+1})$: The bitwise OR of the last $k$ elements of the subsequence starting from the element at index $ix_{k+1}$. Mathematical Intuition and Formulation: The problem involves finding the maximum value of a sequence obtained by XORing the elements of a subsequence of the input array $nums$, where the subsequence can have at most $k$ elements. The solution utilizes dynamic programming and recursion to efficiently explore all possible subsequences and their corresponding XOR values. Derivation of DP Recurrence: The value of a subsequence with size $2k$, with the $k$-th element's index $ix_k$ and $(k+1)$-th element's index $ix_{k+1}$ can be written as: $value(ix_k, ix_{k+1}) = (nums[ix_k-k+1] \lor nums[ix_k-k+2] \lor \dots \lor nums[ix_k]) \oplus (nums[ix_{k+1}] \lor \dots \lor nums[ix_{k+1}+k-1])$ Let $left\_or(ix_k) = nums[ix_k-k+1] \lor nums[ix_k-k+2] \lor \dots \lor nums[ix_k]$ $right\_or(ix_{k+1}) = nums[ix_{k+1}] \lor \dots \lor nums[ix_{k+1}+k-1]$ Then $value(ix_k, ix_{k+1}) = left\_or(ix_k) \oplus right\_or(ix_{k+1})$ To find the maximum value of any subsequence of size $2k$, we can iterate over all possible $ix_k$ and calculate the value of the subsequence. To avoid redundant calculations, we can use dynamic programming to store the intermediate results. We can define a DP table, $dp$, as follows: - $dp[ix_k]$: Stores the set of all possible values of $left\_or(ix_k)$. The base case for $dp$ is as follows: - $dp[ix_k] = \{0\}$ for $ix_k < k - 1$ The recursive case for $dp$ is as follows: - $dp[ix_k] = dp[ix_k-1] \cup \{v \lor nums[ix_k] \text{ for } v \text{ in } dp[ix_k-1]\}$ for $ix_k >= k - 1$ The $dp_{rev}$ table can be defined similarly, but in terms of $dp$ by reversing the input array $nums$ and using the same logic. Finally, the maximum value of any subsequence of size $2k$ can be calculated as follows: $\max\_value = \max_{ix_k=k-1}^{N-k-1} \max_{v_l \in dp[ix_k], v_r \in dp_{rev}[ix_k+1]} (v_l \oplus v_r)$ This approach effectively breaks down the problem into smaller, overlapping subproblems and uses dynamic programming to store and reuse the results of these subproblems, avoiding redundant calculations and improving efficiency. # Code ```python3 [] from collections import defaultdict as dd from copy import deepcopy from functools import reduce, lru_cache import operator def or_reduce(ixs , nums): return reduce(operator.or_, map( lambda ix : nums[ix] , ixs ), 0) class Solution: def maxValue(self, nums: List[int], k: int) -> int: N = len(nums) nums_rev = list(reversed(nums)) def dfs_util(nums, kk): N = len(nums) dp = dd(lambda : set()) @lru_cache(maxsize=None) def f_dp(ix , k): if(ix<0): return set() if(k<0): return set() if(k==0): return set([0]) if(ix == 0): if(k==1): return set([nums[0]]) num = nums[ix] poss = set() for v in f_dp(ix-1,k): poss.add(v) for v in f_dp(ix-1,k-1): poss.add(v | num) return poss for ix in range(N): dp[ix] = dp[ix-1].union(f_dp(ix,kk)) return dp dp = dfs_util(nums,k) dp_rev = dfs_util(nums_rev,k) res = None for i in range(N): j = i + 1 j1 = N-1-(j) if(not 0<=j<N): continue # print(f"i,j={i,j}, {dp[i]} ^ {dp_rev[j1]}") for v_i in dp[i]: for v_j in dp_rev[j1]: res1 = v_i ^ v_j if(res is None or res1 > res): res = res1 return res ```
0
1
['Math', 'Dynamic Programming', 'Bit Manipulation', 'Recursion', 'Memoization', 'Python3']
0
find-the-maximum-sequence-value-of-array
DP + Bitmask [EXPLAINED]
dp-bitmask-explained-by-r9n-o6wf
IntuitionFind the maximum value that can be achieved by splitting an array into two parts and applying some conditions on those parts. We need to check if we ca
r9n
NORMAL
2025-02-06T06:49:36.455568+00:00
2025-02-06T06:49:36.455568+00:00
12
false
# Intuition Find the maximum value that can be achieved by splitting an array into two parts and applying some conditions on those parts. We need to check if we can split the array such that the two parts have certain properties, and we need to track these properties to calculate the maximum possible value. # Approach I used DP to track the possible configurations in both directions of the array (prefix and suffix). I created two 2D arrays dpPref and dpSuff where each element stores whether a certain configuration is achievable with the current part of the array. Then, by iterating over possible configurations and checking both prefix and suffix arrays, I calculated the maximum value that can be obtained from the given constraints. # Complexity - Time complexity: O(n * 2^7 * k), where n is the length of the array, 2^7 represents the number of possible bitmask configurations for the elements (since we are working with 7 bits), and k is the number of parts we can split the array into. - Space complexity: O(n * 2^7 * k) because we are storing the results of the dynamic programming process for each element and configuration. # Code ```kotlin [] class Solution { fun maxValue(num: IntArray, k: Int): Int { val n = num.size val dpPref = Array(n) { Array(1 shl 7) { BooleanArray(k + 1) } } val dpSuff = Array(n) { Array(1 shl 7) { BooleanArray(k + 1) } } for (i in 0 until n) { for (j in 0 until (1 shl 7)) { for (l in 0..k) { dpPref[i][j][l] = false dpSuff[i][j][l] = false } } } dpPref[0][num[0]][1] = true dpPref[0][0][0] = true for (i in 1 until n) { dpPref[i][num[i]][1] = true dpPref[i][0][0] = true for (mask in 0 until (1 shl 7)) { for (len in 1..k) { dpPref[i][mask][len] = dpPref[i][mask][len] or dpPref[i - 1][mask][len] } for (s in mask downTo 0) { if (mask != (s or num[i])) continue for (len in 1..k) { dpPref[i][mask][len] = dpPref[i][mask][len] or dpPref[i - 1][s][len - 1] } } } } dpSuff[n - 1][num[n - 1]][1] = true dpSuff[n - 1][0][0] = true for (i in n - 2 downTo 0) { dpSuff[i][num[i]][1] = true dpSuff[i][0][0] = true for (mask in 0 until (1 shl 7)) { for (len in 1..k) { dpSuff[i][mask][len] = dpSuff[i][mask][len] or dpSuff[i + 1][mask][len] } for (s in mask downTo 0) { if (mask != (s or num[i])) continue for (len in 1..k) { dpSuff[i][mask][len] = dpSuff[i][mask][len] or dpSuff[i + 1][s][len - 1] } } } } for (ans in (1 shl 7) - 1 downTo 0) { for (i in (1 shl 7) - 1 downTo 0) { val first = i val second = ans xor i for (idx in 0 until n - 1) { if (dpPref[idx][first][k] && dpSuff[idx + 1][second][k]) { return ans } } } } return 0 } } ```
0
0
['Array', 'Dynamic Programming', 'Bit Manipulation', 'Memoization', 'Suffix Array', 'Bitmask', 'Kotlin']
0
find-the-maximum-sequence-value-of-array
Dp
dp-by-lauel24-ns2m
Code
lauel24
NORMAL
2025-01-17T10:07:20.992521+00:00
2025-01-17T10:07:20.992521+00:00
6
false
# Code ```csharp [] public class Solution { const int M = 128; const int MAX_POSSIBLE = 127; public int MaxValue(int[] nums, int k) { int n = nums.Length; // keep track by length (number of selected numbers) of all // numbers we can construct (by doing 'or' of selected numbers) List<bool[]> lefts = new(k + 1); // when no number are selected (length 0) we can construct 0 numbers, // for others length there are only M possible outcomes lefts.Add([]); List<bool[]> rights = new(k + 1); rights.Add([]); // for each position we store contructed numbers for length k bool[][] rightsStoredK = new bool[n][]; int max = 0; // if we take more there are not enough numbers to construct second half of size k int end = n - k; for (int i = n - 1; i >= k; i--) { Fill(rights, nums[i], k); if (rights.Count <= k) continue; rightsStoredK[i] = new bool[M]; rights[k].CopyTo(rightsStoredK[i], 0); } for (int i = 0; i < end; i++) { Fill(lefts, nums[i], k); if (lefts.Count <= k) continue; int i2 = i + 1; for (int l = 1; l < M; l++) { if (!lefts[k][l]) continue; for (int l2 = 1; l2 < M; l2++) { if (!rightsStoredK[i2][l2]) continue; int newMax = l ^ l2; if (newMax == MAX_POSSIBLE) return MAX_POSSIBLE; if (newMax > max) max = newMax; } } } return max; } void Fill(List<bool[]> list, int num, int k) { if (list.Count <= k) list.Add(new bool[M]); for (int j = list.Count - 2; j > 0; j--) { for (int l = 1; l < M; l++) { if (!list[j][l]) continue; list[j + 1][l | num] = true; } } list[1][num] = true; } } ```
0
0
['C#']
0
find-the-maximum-sequence-value-of-array
C++ Well Commented Code
c-well-commented-code-by-niteshkumartiwa-mn25
Code\ncpp []\nclass Solution {\n vector<vector<vector<int>>> getAllPossibleORValues(vector<int> &A, int k) {\n int n= A.size();\n vector<vector
niteshkumartiwari
NORMAL
2024-12-06T05:32:34.238700+00:00
2024-12-06T05:32:34.238733+00:00
9
false
# Code\n```cpp []\nclass Solution {\n vector<vector<vector<int>>> getAllPossibleORValues(vector<int> &A, int k) {\n int n= A.size();\n vector<vector<vector<int>>> dp(n, vector<vector<int>>(k+1, vector<int>(129)));\n dp[0][0][0] = 1; // In [0, 0] elements, we can get 0 OR value with 0 elements selected\n dp[0][1][A[0]] = 1; // In [0, 0] elements, we can get nums[0] OR value with 1 elements selected\n\n for(int i=1;i<n;i++) {\n dp[i][0][0] =1; // In [0, i] elements , we can get 0 OR value with 0 elements selected\n for(int j=1;j<=k;j++) {\n for(int or1 = 0; or1 <= 128; or1++) {\n // skip the ith element to get subseq\n if(dp[i][j][or1]==0) // If not already set by line 18 earlier\n dp[i][j][or1] = dp[i-1][j][or1];\n\n // take the ith element\n int nextOR = A[i] | or1;\n if(dp[i-1][j-1][or1]==1) // Only setting the value if its possible , so that its not reset\n dp[i][j][nextOR] = dp[i-1][j-1][or1];\n }\n }\n }\n\n return dp;\n }\npublic:\n int maxValue(vector<int>& nums, int k) {\n int n= nums.size();\n vector<int> copy = nums;\n auto left = getAllPossibleORValues(nums, k);\n reverse(begin(copy), end(copy));\n auto right = getAllPossibleORValues(copy, k);\n reverse(begin(right), end(right));\n int result =0;\n\n for(int i=k-1;(i+k) < n;i++) {\n for(int leftOR=0;leftOR <= 128 ; leftOR++) {\n for(int rightOR=0;rightOR <= 128 ; rightOR++) {\n if(left[i][k][leftOR] && right[i+1][k][rightOR]) {\n result = max(result, leftOR ^ rightOR);\n }\n }\n }\n }\n\n return result;\n }\n};\n```
0
0
['C++']
0
find-the-maximum-sequence-value-of-array
Merge Dp || Prefix Suffix Dp with bitmask || Partition Dp || C++
merge-dp-prefix-suffix-dp-with-bitmask-p-21go
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
oreocraz_273
NORMAL
2024-10-12T14:19:18.802984+00:00
2024-10-12T14:19:18.803006+00:00
7
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n\nint n,k;\nvector<int> a;\n\n bool f(int i,int j,int mask,vector<vector<vector<int>>>& dp)\n {\n if(i>=n)\n return j==k;\n \n\n if(dp[i][j][mask]!=-1)\n return dp[i][j][mask];\n\n bool nt=0,t=0;\n\n nt=f(i+1,j,mask,dp);\n if(j<k)\n t=f(i+1,j+1,mask|a[i],dp);\n\n return dp[i][j][mask]=t || nt;\n \n }\n int maxValue(vector<int>& b, int k) {\n \n this->a=b;\n this->n=b.size();\n this->k=k;\n\n vector<vector<vector<int>>> dp1(n+1,vector<vector<int>>(k+1,vector<int>(128,-1)));\n vector<vector<vector<int>>> dp2(n+1,vector<vector<int>>(k+1,vector<int>(128,-1)));\n\n f(0,0,0,dp1);\n reverse(a.begin(),a.end());\n f(0,0,0,dp2);\n\n int ans=0;\n\n for(int i=1;i<n;i++)\n {\n for(int x=0;x<128;x++)\n {\n for(int y=0;y<128;y++)\n {\n if(i>=k && i<=(n-k))\n {\n if(dp1[i][k][x]==-1 || dp2[n-i][k][y]==-1) continue;\n\n \n if(dp1[i][k][x] && dp2[n-i][k][y])\n {\n ans=max(ans,x^y);\n }\n \n }\n }\n }\n }\n\n return ans;\n\n\n\n }\n};\n```
0
0
['Dynamic Programming', 'Bit Manipulation', 'Bitmask', 'C++']
0
find-the-maximum-sequence-value-of-array
DP | Memoization | C++
dp-memoization-c-by-ayushkriitkgp-8ipl
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
ayushkriitkgp
NORMAL
2024-10-07T14:37:56.799572+00:00
2024-10-07T14:37:56.799604+00:00
27
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n int n;\n\n // the DP table (dp1 and dp2) is used to store whether it\'s possible to select a subsequence of exactly k elements with a particular bitwise OR result up to a given index.\n\n // dp[3][2][7]: This would store 1 if you can pick exactly 2 elements from the first three elements (nums[0], nums[1], nums[2]), such that their OR result is 7.\n\n //states of dp -> {index, length of subsequence, or of subsequence} //3d\n int solve(int i,int x, int oro, vector<int>& nums, int k, vector<vector<vector<int>>> &dp) {\n if (i >= n) {\n return x==k;\n }\n\n if (dp[i][x][oro] != -1) return dp[i][x][oro];\n\n bool take = 0, notTake = 0;\n\n if(x<k) take = solve(i+1,x+1,oro|nums[i], nums, k, dp);\n notTake = solve(i+1,x,oro,nums,k,dp);\n\n return dp[i][x][oro] = take + notTake;\n }\n\n int maxValue(vector<int>& nums, int k) {\n n = nums.size();\n vector<int> ds;\n vector<vector<vector<int>>> dp1(n+1,vector<vector<int>>(k+1, vector<int>(129,-1))); //prefix\n vector<vector<vector<int>>> dp2(n+1,vector<vector<int>>(k+1, vector<int>(129,-1))); //suffix\n solve(0,0,0,nums,k,dp1);\n reverse(nums.begin(),nums.end());\n solve(0,0,0,nums,k,dp2);\n\n int ans = 0;\n\n for(int i=k; i<=n-k; i++){\n for(int or1=0; or1<128; or1++){\n for(int or2=0; or2<128; or2++){\n if(dp1[i][k][or1]==-1 || dp2[n-i][k][or2]==-1) continue;\n if(dp1[i][k][or2] && dp2[n-i][k][or2]){\n ans = max(ans, or1^or2);\n }\n }\n }\n }\n\n return ans;\n }\n\n};\n```
0
0
['C++']
0
find-the-maximum-sequence-value-of-array
[DP] 2 Solutions | Brute Force, DP
dp-2-solutions-brute-force-dp-by-shahsb-9v0h
GOAL:\nYou need to find a subsequence of length 2*k in the given array nums such that:\n+ The subsequence is split into two halves.\n+ Compute the OR operation
shahsb
NORMAL
2024-10-07T02:39:02.209128+00:00
2024-10-08T03:07:33.578899+00:00
11
false
# GOAL:\nYou need to **find a subsequence** of length `2*k` in the given array nums such that:\n+ The subsequence is split into two halves.\n+ Compute the OR operation for each half.\n+ XOR the results of these OR operations.\n+ The goal is to **maximize** this XOR value.\n\n# Solution-1: Brute Force -- TLE -- 567 / 640 TCs passed -- 88.59%\n\n### IDEA:\n+ **Generate all possible subsequences** of length 2*k and compute the value as defined. Then, find the maximum value.\n\n### Complexity:\n+ **Time Complexity:** `O((n2k)\u22C52k)`\n\t\t+ Where, `(n2k)` ---> is the number of ways to choose 2*k elements from n.\n+ **Space Complexity:** `O(2k)` for storing the subsequence.\n\n### CODE:\n```\nclass Solution {\npublic:\n int maxValue(vector<int>& nums, int k) \n {\n return bruteForce(nums, k);\n }\n\nprivate:\n // TLE -- 567 / 640 TCs passed -- 88.59%\n int bruteForce(const vector<int>& nums, int k) \n {\n int n = nums.size();\n int maxXor = 0;\n\n vector<int> seq(2 * k);\n function<void(int, int, int)> generate = [&](int start, int depth, int len) \n\t\t{\n if (depth == 2 * k) {\n int leftOr = 0, rightOr = 0;\n for (int i = 0; i < k; ++i) leftOr |= seq[i];\n for (int i = k; i < 2 * k; ++i) rightOr |= seq[i];\n maxXor = max(maxXor, leftOr ^ rightOr);\n return;\n }\n for (int i = start; i <= n - (2 * k - depth); ++i) {\n seq[depth] = nums[i];\n generate(i + 1, depth + 1, len + 1);\n }\n };\n\n generate(0, 0, 0);\n return maxXor;\n }\n\n};\n```\n\n\n# Solution-2: BITMASK DP \n### Idea:\n+ Tackle the problem of dividing an array into two non-overlapping subsequences of size \nk, each yielding an OR value, which are then XORed for a maximum value.\n+ **Left and Right Subsequences:** Calculate possible OR values for left subsequences and right subsequences separately.\n+ **Non-Overlapping Check:** Ensure subsequences do not overlap, combining their OR values for maximum XOR.\n### CODE:\n```\nclass Solution\n{\npublic:\n int maxValue(vector<int>& nums, int k)\n {\n return sol2DP(nums, k);\n }\n\nprivate:\n public:\n int sol2DP(vector<int>& nums, int k)\n {\n int n = nums.size();\n \n // Initialize DP arrays\n vector<vector<vector<int>>> dp1(n + 1, vector<vector<int>>(k + 1, vector<int>(128, 0)));\n vector<vector<vector<int>>> dp2(n + 1, vector<vector<int>>(k + 1, vector<int>(128, 0)));\n \n // Compute left subsequences\n vector<vector<int>> dp(k + 1, vector<int>(128, 0));\n dp[0][0] = 1;\n for (int i = 0; i < n; ++i) \n {\n for (int j = k - 1; j >= 0; --j) {\n for (int mask = 0; mask < 128; ++mask) {\n if (dp[j][mask]) {\n dp[j + 1][mask | nums[i]] = 1;\n }\n }\n }\n for (int j = 0; j <= k; ++j) {\n for (int mask = 0; mask < 128; ++mask) {\n dp1[i][j][mask] = dp[j][mask];\n }\n }\n }\n \n // Reset dp array\n dp.assign(k + 1, vector<int>(128, 0));\n dp[0][0] = 1;\n\n // Compute right subsequences\n for (int i = n - 1; i >= 0; --i) \n {\n for (int j = k - 1; j >= 0; --j) {\n for (int mask = 0; mask < 128; ++mask) {\n if (dp[j][mask]) {\n dp[j + 1][mask | nums[i]] = 1;\n }\n }\n }\n for (int j = 0; j <= k; ++j) {\n for (int mask = 0; mask < 128; ++mask) {\n dp2[i][j][mask] = dp[j][mask];\n }\n }\n }\n\n int res = 0;\n\n // Find max XOR value of non-overlapping subsequences\n for (int i = 0; i < n - 1; ++i) \n {\n if (i + 1 < k || n - i - 1 < k) continue;\n\n for (int mask1 = 0; mask1 < 128; ++mask1) {\n for (int mask2 = 0; mask2 < 128; ++mask2) {\n if (dp1[i][k][mask1] && dp2[i + 1][k][mask2]) {\n res = max(res, mask1 ^ mask2);\n }\n }\n }\n }\n\n return res;\n }\n};\n```
0
0
['Dynamic Programming', 'C']
0
find-the-maximum-sequence-value-of-array
beats 100/98.67%
beats-1009867-by-ranilmukesh-s8z9
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
ranilmukesh
NORMAL
2024-10-02T19:33:42.738229+00:00
2024-10-02T19:33:42.738250+00:00
25
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```java []\nclass Solution {\n int [][][] prefix;\n int [][][] suffix;\n public int maxValue(int[] nums, int k) {\n int ans = 0;\n prefix = new int [nums.length][128][2];\n suffix = new int [nums.length][128][2];\n compute(nums);\n for(int lor = 1;lor<128;lor++){\n for(int ror=1;ror<128;ror++){\n if(isPossible(nums,lor,ror,k)){\n ans = Math.max(ans,lor^ror);\n }\n }\n }\n return ans;\n }\n\n private boolean isPossible(int[] nums,int lor,int ror,int k){\n int n = nums.length;\n for(int i=0;i<n-1;i++){\n int pmin = prefix[i][lor][0];\n int pmax = prefix[i][lor][1];\n int smin = suffix[i+1][ror][0];\n int smax = suffix[i+1][ror][1];\n if(pmin<=k && pmax>=k && smin<=k && smax>=k){\n return true;\n }\n }\n return false;\n }\n \n\n private void compute(int [] nums){\n int n=nums.length;\n for(int [][] arr:prefix){\n for(int [] arrr:arr){\n Arrays.fill(arrr,Integer.MAX_VALUE);\n }\n }\n for(int [][] arr:suffix){\n for(int [] arrr:arr){\n Arrays.fill(arrr,Integer.MAX_VALUE);\n }\n }\n prefix[0][nums[0]][0] = 1;\n prefix[0][nums[0]][1] = 1;\n for(int i=1;i<n;i++){\n for(int j=1;j<128;j++){\n prefix[i][j][0] = prefix[i-1][j][0];\n prefix[i][j][1] = prefix[i-1][j][1];\n }\n prefix[i][nums[i]][0] = 1;\n if(prefix[i][nums[i]][1]==Integer.MAX_VALUE){\n prefix[i][nums[i]][1] = 1;\n }\n //prefix[i][nums[i]][1] = Math.max(prefix[i][nums[i]][1],1);\n \n for(int j=1;j<128;j++){\n if(prefix[i-1][j][0]==Integer.MAX_VALUE) continue;\n int val = j | nums[i];\n prefix[i][val][0] = Math.min(prefix[i][val][0],1+prefix[i-1][j][0]);\n if(prefix[i][val][1]==Integer.MAX_VALUE){\n prefix[i][val][1] = 1+prefix[i-1][j][1];\n }else{\n prefix[i][val][1] = Math.max(prefix[i][val][1],1+prefix[i-1][j][1]);\n }\n }\n }\n\n // suffix\n suffix[n-1][nums[n-1]][0] = 1;\n suffix[n-1][nums[n-1]][1] = 1;\n for(int i=n-2;i>=0;i--){\n for(int j=1;j<128;j++){\n suffix[i][j][0] = suffix[i+1][j][0];\n suffix[i][j][1] = suffix[i+1][j][1];\n }\n suffix[i][nums[i]][0] = 1;\n if(suffix[i][nums[i]][1]==Integer.MAX_VALUE){\n suffix[i][nums[i]][1] = 1;\n }\n //prefix[i][nums[i]][1] = Math.max(prefix[i][nums[i]][1],1);\n \n for(int j=1;j<128;j++){\n if(suffix[i+1][j][0]==Integer.MAX_VALUE) continue;\n int val = j | nums[i];\n suffix[i][val][0] = Math.min(suffix[i][val][0],1+suffix[i+1][j][0]);\n if(suffix[i][val][1]==Integer.MAX_VALUE){\n suffix[i][val][1] = 1+suffix[i+1][j][1];\n }else{\n suffix[i][val][1] = Math.max(suffix[i][val][1],1+suffix[i+1][j][1]);\n }\n }\n }\n }\n}\n```
0
0
['Java']
0
find-the-maximum-sequence-value-of-array
C++ Hard (Python TLE)
c-hard-python-tle-by-lucasschnee-g34i
cpp []\n#include <vector>\n#include <algorithm>\nusing namespace std;\n\nclass Solution {\npublic:\n // Helper function to calculate arr\n void calc(int i
lucasschnee
NORMAL
2024-09-28T02:17:15.306246+00:00
2024-09-28T02:17:15.306280+00:00
2
false
```cpp []\n#include <vector>\n#include <algorithm>\nusing namespace std;\n\nclass Solution {\npublic:\n // Helper function to calculate arr\n void calc(int index, int mask, int k, int N, vector<int>& nums, vector<vector<int>>& arr, vector<vector<vector<int>>>& seen) {\n if (k == 0) {\n arr[index - 1][mask] = 1;\n return;\n }\n if (index == N) {\n return;\n }\n if (seen[index][mask][k]) {\n return;\n }\n seen[index][mask][k] = 1;\n\n calc(index + 1, mask, k, N, nums, arr, seen);\n calc(index + 1, mask | nums[index], k - 1, N, nums, arr, seen);\n }\n\n // Helper function to calculate arr_suf\n void calc_suf(int index, int mask, int k, int N, vector<int>& nums, vector<vector<int>>& arr_suf, vector<vector<vector<int>>>& seen) {\n if (k == 0) {\n arr_suf[index + 1][mask] = 1;\n return;\n }\n if (index < 0) {\n return;\n }\n if (seen[index][mask][k]) {\n return;\n }\n seen[index][mask][k] = 1;\n\n calc_suf(index - 1, mask, k, N, nums, arr_suf, seen);\n calc_suf(index - 1, mask | nums[index], k - 1, N, nums, arr_suf, seen);\n }\n\n void resetSeen(vector<vector<vector<int>>>& seen, int N, int k) {\n for (int i = 0; i < N; ++i) {\n for (int j = 0; j < 128; ++j) {\n for (int l = 0; l <= k; ++l) {\n seen[i][j][l] = 0;\n }\n }\n }\n }\n\n int maxValue(vector<int>& nums, int k) {\n int N = nums.size();\n\n vector<vector<int>> arr(N, vector<int>(128, 0));\n vector<vector<int>> arr_suf(N, vector<int>(128, 0));\n\n vector<vector<vector<int>>> seen(N, vector<vector<int>>(128, vector<int>(k + 1, 0)));\n\n // Execute calculations\n calc(0, 0, k, N, nums, arr, seen);\n\n // Reset all elements of seen to 0\n resetSeen(seen, N, k);\n\n calc_suf(N - 1, 0, k, N, nums, arr_suf, seen);\n\n // Update arr and arr_suf\n for (int i = 1; i < N; ++i) {\n for (int j = 0; j < 128; ++j) {\n arr[i][j] |= arr[i - 1][j];\n }\n }\n\n for (int i = N - 2; i >= 0; --i) {\n for (int j = 0; j < 128; ++j) {\n arr_suf[i][j] |= arr_suf[i + 1][j];\n }\n }\n\n int best = 0;\n\n // Find the best result\n for (int i = 0; i < N - 1; ++i) {\n for (int j = 0; j < 128; ++j) {\n for (int l = 0; l < 128; ++l) {\n if (arr[i][j] & arr_suf[i + 1][l]) {\n best = max(best, j ^ l);\n }\n }\n }\n }\n\n return best;\n }\n};\n\n```
0
0
['C++']
0
find-the-maximum-sequence-value-of-array
Easy to understand with refrence of standard problem
easy-to-understand-with-refrence-of-stan-v17j
Intuition\nIntution came from maximum subarray XOR in a given array problem\n\n# Approach\nIf we take refrence of (maximum subarray XOR in a given array) proble
thinker37
NORMAL
2024-09-27T06:07:13.084146+00:00
2024-09-27T06:07:13.084184+00:00
35
false
# Intuition\n*Intution came from* **maximum subarray XOR in a given array** problem\n\n# Approach\nIf we take refrence of (maximum subarray XOR in a given array) problem then we have to replace element of array with different possible **OR** value till **ith** index and then apply algorithm.\n\n# Complexity\n- Time complexity:\n**O(n * k * 128)** + **O(n * k * 128)** + 2 * (n * 128 * 7)\n\n- Space complexity:\n\n**O(n * k * 128)**\n# Code\n```cpp []\nclass Node {\npublic:\n vector<Node*> bit;\n Node() { bit.assign(2, NULL); }\n};\nclass Trie {\n Node* root;\n\npublic:\n Trie(Node* Root) { root = Root; }\n void insert(int mask) {\n \n Node* ptr = root;\n for(int i=6;i>=0;i--){\n int ind=((mask>>i)&1);\n \n if(ptr->bit[ind]==NULL)ptr->bit[ind]=new Node();\n ptr=ptr->bit[ind];\n }\n }\n int give_max_unmatch(int mask) {\n \n Node *ptr=root;\n int ans=0;\n for(int i=6;i>=0;i--){\n int ind=((mask>>i)&1);\n if(ptr->bit[1-ind]){\n ans+=1<<i;\n ptr=ptr->bit[1-ind];\n }\n else if(ptr->bit[ind]){\n ptr=ptr->bit[ind];\n }\n }\n return ans;\n }\n};\nclass Solution {\n\npublic:\n int maxValue(vector<int>& nums, int k) {\n const int n = nums.size();\n int dp1[n + 1][128], dp2[n + 1][128];\n int memo1[n + 1][k+1][129], memo2[n + 1][k+1][129];\n function<void(int, int, int)> fun1 = [&](int ind, int len, int mask) {\n \n if (len == k)\n { \n for(int i=ind-1;i<n;i++){\n dp1[i][mask] = 1;\n }\n return;}\n if (ind >= n)\n return;\n if (memo1[ind][len][mask] != -1)\n return;\n fun1(ind + 1, len + 1, (mask | nums[ind]));\n fun1(ind + 1, len, mask);\n memo1[ind][len][mask] = 1;\n };\n memset(dp1, 0, sizeof(dp1));\n memset(memo1, -1, sizeof(memo1));\n fun1(0, 0, 0);\n memset(dp2, 0, sizeof(dp2));\n memset(memo2, -1, sizeof(memo2));\n function<void(int, int, int)> fun2 = [&](int ind, int len, int mask) {\n \n if (len == k)\n { \n for(int j=ind+1;j>=0;j--){\n dp2[j][mask] = 1;\n }\n return;}\n if (ind < 0)\n return;\n if (memo2[ind][len][mask] != -1)\n return;\n fun2(ind - 1, len + 1, (mask | nums[ind]));\n fun2(ind - 1, len, mask);\n memo2[ind][len][mask] = 1;\n };\n fun2(n - 1, 0, 0);\n vector<Node*> Roots(n);\n for (int i = 0; i < n; i++) {\n Node* root = new Node();\n Trie T(root);\n for (int j = 0; j < 128; j++) {\n if (dp1[i][j])\n { T.insert(j); }\n }\n \n Roots[i]=root;\n }\n \n int ans = 0;\n for (int i = n - 1; i > 0; i--) {\n Trie T(Roots[i - 1]);\n \n for (int j = 0; j < 128; j++) {\n if (dp2[i][j]) {\n ans = max(ans, T.give_max_unmatch(j));\n \n }\n }\n }\n return ans;\n }\n};\n```
0
0
['Dynamic Programming', 'Bit Manipulation', 'Trie', 'Bitmask', 'C++']
0
find-the-maximum-sequence-value-of-array
Simple Rust solution
simple-rust-solution-by-abhineetraj1-qf7l
Intuition\nThe problem involves finding the maximum value obtainable from a combination of bitwise operations on subsets of an integer array. The goal is to spl
abhineetraj1
NORMAL
2024-09-26T16:43:41.408292+00:00
2024-09-26T16:43:41.408330+00:00
4
false
# Intuition\nThe problem involves finding the maximum value obtainable from a combination of bitwise operations on subsets of an integer array. The goal is to split the array into two parts, with each part contributing to a maximum XOR value based on a specified number of elements, `k`. The intuition is to use a dynamic programming approach to keep track of all possible XOR values that can be formed by using up to `k` elements from both the left and right parts of the array.\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. **Dynamic Programming Tables**: Use two dynamic programming tables (`left` and `right`) to store sets of possible XOR values for subarrays:\n - `left[i][j]` represents all possible XOR values using up to `j` elements from the first `i` elements of the array.\n - `right[i][j]` does the same for the last `n-i` elements.\n \n2. **Initialization**: Start with base cases where no elements yield an XOR of 0.\n\n3. **Filling the Tables**:\n - For the `left` table, iterate through the elements and update the possible XOR values. For each count of selected elements, combine previous values with the current element\'s contribution.\n - Similarly, fill the `right` table but iterate from the end of the array backward.\n\n4. **Maximizing the Result**: After constructing both tables, iterate through them to find the maximum XOR of values from `left` and `right` that use exactly `k` elements.\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(n<sup>2</sup>\u22C5k)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n\u22C5k)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```rust []\nuse std::collections::HashSet;\nuse std::convert::TryInto;\n\nimpl Solution {\n pub fn max_value(nums: Vec<i32>, k: i32) -> i32 {\n let n = nums.len();\n let k = k.try_into().unwrap();\n let mut left = vec![vec![HashSet::new(); k + 1]; n];\n let mut right = vec![vec![HashSet::new(); k + 1]; n];\n\n left[0][0].insert(0);\n left[0][1].insert(nums[0]);\n\n for i in 1..(n - k) {\n left[i][0].insert(0);\n for j in 1..=k {\n left[i][j] = left[i - 1][j].clone();\n let previous = left[i - 1][j - 1].clone();\n for v in previous {\n left[i][j].insert(v | nums[i]);\n }\n }\n }\n\n right[n - 1][0].insert(0);\n right[n - 1][1].insert(nums[n - 1]);\n let mut result = 0;\n\n if k == 1 {\n for &l in &left[n - 2][k] {\n result = result.max(l ^ nums[n - 1]);\n }\n }\n\n for i in (k..n - 1).rev() {\n right[i][0].insert(0);\n for j in 1..=k {\n right[i][j] = right[i + 1][j].clone();\n let previous = right[i + 1][j - 1].clone();\n for v in previous {\n right[i][j].insert(v | nums[i]);\n }\n }\n for &l in &left[i - 1][k] {\n for &r in &right[i][k] {\n result = result.max(l ^ r);\n }\n }\n }\n\n result\n }\n}\n\n```
0
0
['Rust']
0
find-the-maximum-sequence-value-of-array
CPP solution ( Very Good Question)
cpp-solution-very-good-question-by-npkr-xgrn
Code\ncpp []\nclass Solution {\npublic:\n vector<vector<int>> findMin(vector<int> &nums) {\n int n = nums.size();\n vector<vector<int>> miniCha
npkr
NORMAL
2024-09-26T09:14:37.169598+00:00
2024-09-26T09:14:37.169631+00:00
11
false
# Code\n```cpp []\nclass Solution {\npublic:\n vector<vector<int>> findMin(vector<int> &nums) {\n int n = nums.size();\n vector<vector<int>> miniChar(n, vector<int>(128, INT_MAX));\n miniChar[0][0] = 0;\n miniChar[0][nums[0]] = 1;\n for (int i = 1; i < n; i++) {\n miniChar[i] = vector<int>(miniChar[i - 1]);\n for (int j = 0; j < 128; j++) {\n if (miniChar[i - 1][j] != INT_MAX) {\n int num = j | nums[i];\n miniChar[i][num] = min(miniChar[i][num], 1 + miniChar[i - 1][j]);\n }\n }\n }\n return miniChar;\n }\n\n vector<vector<int>> findMax(vector<int> &nums) {\n int n = nums.size();\n vector<vector<int>> maxChar(n, vector<int>(128, INT_MIN));\n maxChar[0][0] = 0;\n maxChar[0][nums[0]] = 1;\n for (int i = 1; i < n; i++) {\n maxChar[i] = vector<int>(maxChar[i - 1]);\n for (int j = 0; j < 128; j++) {\n if (maxChar[i - 1][j] != INT_MIN) {\n int num = j | nums[i];\n maxChar[i][num] = max(maxChar[i][num], 1 + maxChar[i - 1][j]);\n }\n }\n }\n return maxChar;\n }\n\n bool check(int l, int r, int k, int orr, vector<vector<int>> &minCharL, vector<vector<int>> &maxCharL, vector<vector<int>> &minCharR, vector<vector<int>> &maxCharR) {\n int n = minCharL.size();\n int minimumChar, maximumChar;\n if (l == 0) {\n minimumChar = minCharL[r][orr];\n maximumChar = maxCharL[r][orr];\n } else {\n minimumChar = minCharR[n - l - 1][orr];\n maximumChar = maxCharR[n - l - 1][orr];\n }\n if(minimumChar==INT_MIN || maximumChar==INT_MAX)\n return false;\n return (k >= minimumChar && k <= maximumChar);\n }\n\n bool isPossible(int left_or, int right_or, int k, vector<vector<int>> &minCharL, vector<vector<int>> &maxCharL, vector<vector<int>> &minCharR, vector<vector<int>> &maxCharR) {\n // cout<<left_or<<" "<<right_or<<endl;\n int n = minCharL.size();\n for (int i = k - 1; i <= n - k - 1; i++) {\n if (check(0, i, k,left_or, minCharL, maxCharL, minCharR, maxCharR) && check(i + 1, n - 1, k,right_or, minCharL, maxCharL, minCharR, maxCharR)) { \n //\n return true;\n }\n }\n return false;\n }\n\n vector<int> revrse(vector<int> nums) {\n reverse(nums.begin(), nums.end());\n return nums;\n }\n\n int maxValue(vector<int>& nums, int k) {\n int ans = 0;\n vector<int> rnums = revrse(nums);\n vector<vector<int>> minCharL = findMin(nums);\n vector<vector<int>> maxCharL = findMax(nums);\n vector<vector<int>> minCharR = findMin(rnums);\n vector<vector<int>> maxCharR = findMax(rnums);\n int n=nums.size();\n // for(int j=0;j<128;j++){\n // for(int i=0;i<nums.size();i++){\n \n // cout<<maxCharR[i][j]<<" ";\n // }cout<<endl;\n // }\n for (int left_or = 0; left_or < 128; left_or++) {\n for (int right_or = 0; right_or < 128; right_or++) {\n if (isPossible(left_or, right_or, k, minCharL, maxCharL, minCharR, maxCharR)) {\n // cout<<"hi"<<left_or<<" "<<right_or<<endl;\n ans = max(ans, left_or ^ right_or);\n \n }\n }\n }\n return ans;\n }\n};\n\n```
0
0
['C++']
0
find-the-maximum-sequence-value-of-array
C++
c-by-intermsof-rg4k
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
intermsof
NORMAL
2024-09-22T22:14:13.836670+00:00
2024-09-22T22:14:13.836688+00:00
10
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n int maxValue(vector<int>& nums, int k) {\n vector<vector<int> > \n C(nums.size(), vector<int>(128, 0)), \n D(nums.size(), vector<int>(128, 0)),\n tempC(nums.size(), vector<int>(128, 0)),\n tempD(nums.size(), vector<int>(128, 0));\n\n for (int choose = 1; choose <= k; ++choose) {\n for (int index = choose - 1; index < nums.size(); ++index) {\n const int reverse_index = nums.size() - 1 - index;\n const int reverse_num = nums[reverse_index],\n num = nums[index];\n if (choose == 1) {\n tempC[reverse_index][reverse_num - 1] = 1;\n tempD[index][num - 1] = 1; \n } else {\n for (int i = 0; i < 128; ++i) {\n if (C[reverse_index + 1][i] == 1) {\n tempC[reverse_index][(reverse_num | (i + 1)) - 1] = 1;\n }\n if (D[index - 1][i] == 1) {\n tempD[index][(num | (i + 1)) - 1] = 1;\n }\n }\n }\n if (index != choose - 1) {\n for (int i = 0; i < 128; ++i) {\n if (tempC[reverse_index + 1][i] == 1) tempC[reverse_index][i] = 1;\n if (tempD[index - 1][i] == 1) tempD[index][i] = 1;\n }\n }\n }\n\n C = tempC;\n D = tempD;\n tempC = vector<vector<int> > (nums.size(), vector<int>(128, 0)),\n tempD = vector<vector<int> > (nums.size(), vector<int>(128, 0));\n }\n\n\n int result = 0;\n for (int split = k - 1; split < nums.size() - k; ++split) {\n // for (int i = 0; i < 128; ++i) {\n // if (D[split][i] == 1) cout << split << " D: " << i + 1 << endl;\n // if (C[split + 1][i] == 1) cout << split << " C: " << i + 1 << endl;\n // }\n for (int i = 0; i < 128; ++i) \n if (D[split][i] == 1)\n for (int j = 0; j < 128; ++j)\n if (C[split + 1][j] == 1) \n result = max ((i + 1) ^ (j + 1), result);\n // if (D[split][i] == 1)\n // for (int j = 0; j < 128; ++j)\n // if (C[split + 1][j] == 1)\n // result = max ((i + 1) ^ (j + 1), result);\n }\n\n return result;\n }\n};\n\n/*\n110\n111\n\nSuppose we split the input into two parts\n let S(i), T(i) denote the set of possible OR values in [0: i], [i + 1: ] respectively\n and denote U(i) = {s XOR t | s in S(i), t in T(i)}\n\nLet MaxValueSplit(i) = Max(U(i))\n\nDenote X = {Max(U(i)) | k - 1 <= i < nums.size() - k }\n\nAnswer = Max(X)\n\nLet n = nums.size()\nDenote C(a,b) = the set of possible OR values of all size b subsequences of nums[a:]\n Let X = b == 1 ? {nums[a]} : {nums[a] | x, x in C(a + 1, b - 1)}\n Let Y = b <= n - a - 1 ? C(a + 1, b) : empty\n C(a,b) = X U Y\n\nDenote D(a,b) = the set of possible OR values of all size b subsequences of nums[0:a]\n Let X = b == 1 ? {nums[a]} : {nums[a] | x, x in D(a - 1, b - 1)}\n Let Y = b <= a ? C(a - 1, b) : empty\n\nWhat are the possible splits i: k - 1 <= i < nums.size() - k\n\nFor every split, compute the max over \n D(i, k) XOR C(x, k) for i < x <= nums.size() - k\n\nIterate from j = 1 to j = k for k <= i <= nums.size() - k\ne \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n*/\n```
0
0
['C++']
0
find-the-maximum-sequence-value-of-array
C++ Prefix and Suffix Boolean Dp table.
c-prefix-and-suffix-boolean-dp-table-by-cc78e
Intuition\n1. "Or" of all numbers will be less than pow(2,7)=128.\n2. Create Prefix and Suffix dp tables. \n3. prefix[i][j][m] = true means it is possible to fi
spike02
NORMAL
2024-09-21T14:14:17.640741+00:00
2024-09-21T14:14:17.640761+00:00
18
false
# Intuition\n1. "Or" of all numbers will be less than pow(2,7)=128.\n2. Create Prefix and Suffix dp tables. \n3. prefix[i][j][m] = true means it is possible to find a subsequence of size m starting from 0 index and ending at index i-1 and the "Or" of the chosen elements comes as j.\n4. suffix[i][j][m] = true means it is possible to find a subsequence of size m starting at index i and ending at index n-1 and the "Or" of the chosen elements comes as j.\n5. Now for every index i, we will check all the values between [0,127] in prefix table for index i and size m that is true and check all the values between [0,127] in suffix table for index i+1 and size m that is true. For each combination, we will xor the two values.\n\n\n# Complexity\n- Time complexity:\nO(n * k * 128) + O(n * 128 * 128)\n\n- Space complexity:\nO(n * k * 128)\n\n# Code\n```cpp []\nclass Solution {\npublic:\n int maxValue(vector<int>& nums, int k) {\n int n = nums.size();\n vector<vector<vector<bool>>> prefix(n+1, vector<vector<bool>>((1<<7), vector<bool>(k+1, false)));\n vector<vector<vector<bool>>> suffix(n+1, vector<vector<bool>>((1<<7), vector<bool>(k+1, false)));\n prefix[0][0][0] = true;\n for (int i=1; i<=n; i++) {\n for (int j=0; j<(1<<7); j++) {\n for (int m=0; m<=k; m++) {\n if (prefix[i-1][j][m]) {\n prefix[i][j][m] = true;\n if (m+1<=k) {\n prefix[i][j|nums[i-1]][m+1] = true;\n }\n }\n }\n }\n }\n suffix[n][0][0] = true;\n for (int i=n-1; i>=0; i--) {\n for (int j=0; j<(1<<7); j++) {\n for (int m=0; m<=k; m++) {\n if (suffix[i+1][j][m]) {\n suffix[i][j][m] = true;\n if (m+1<=k) {\n suffix[i][j|nums[i]][m+1] = true;\n }\n }\n }\n }\n }\n int ans = 0;\n for (int i=0; i<n; i++) {\n int pi = i+1;\n int si = i+1;\n for (int j=0; j<(1<<7); j++) {\n if (!prefix[pi][j][k]) continue;\n for (int a=0; a<(1<<7); a++) {\n if (!suffix[si][a][k]) continue;\n ans = max(ans, (j ^ a));\n }\n }\n }\n return ans;\n }\n};\n```
0
0
['C++']
0
find-the-maximum-sequence-value-of-array
JAVA 3D suffix and prefix OR
java-3d-suffix-and-prefix-or-by-viratt15-dh60
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
viratt15081990
NORMAL
2024-09-21T12:56:25.198411+00:00
2024-09-21T12:56:25.198433+00:00
21
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```java []\nclass Solution {\n int [][][] prefix;\n int [][][] suffix;\n public int maxValue(int[] nums, int k) {\n int ans = 0;\n prefix = new int [nums.length][128][2];\n suffix = new int [nums.length][128][2];\n compute(nums);\n for(int lor = 1;lor<128;lor++){\n for(int ror=1;ror<128;ror++){\n if(isPossible(nums,lor,ror,k)){\n ans = Math.max(ans,lor^ror);\n }\n }\n }\n return ans;\n }\n\n private boolean isPossible(int[] nums,int lor,int ror,int k){\n int n = nums.length;\n for(int i=0;i<n-1;i++){\n int pmin = prefix[i][lor][0];\n int pmax = prefix[i][lor][1];\n int smin = suffix[i+1][ror][0];\n int smax = suffix[i+1][ror][1];\n if(pmin<=k && pmax>=k && smin<=k && smax>=k){\n return true;\n }\n }\n return false;\n }\n \n\n private void compute(int [] nums){\n int n=nums.length;\n for(int [][] arr:prefix){\n for(int [] arrr:arr){\n Arrays.fill(arrr,Integer.MAX_VALUE);\n }\n }\n for(int [][] arr:suffix){\n for(int [] arrr:arr){\n Arrays.fill(arrr,Integer.MAX_VALUE);\n }\n }\n prefix[0][nums[0]][0] = 1;\n prefix[0][nums[0]][1] = 1;\n for(int i=1;i<n;i++){\n for(int j=1;j<128;j++){\n prefix[i][j][0] = prefix[i-1][j][0];\n prefix[i][j][1] = prefix[i-1][j][1];\n }\n prefix[i][nums[i]][0] = 1;\n if(prefix[i][nums[i]][1]==Integer.MAX_VALUE){\n prefix[i][nums[i]][1] = 1;\n }\n //prefix[i][nums[i]][1] = Math.max(prefix[i][nums[i]][1],1);\n \n for(int j=1;j<128;j++){\n if(prefix[i-1][j][0]==Integer.MAX_VALUE) continue;\n int val = j | nums[i];\n prefix[i][val][0] = Math.min(prefix[i][val][0],1+prefix[i-1][j][0]);\n if(prefix[i][val][1]==Integer.MAX_VALUE){\n prefix[i][val][1] = 1+prefix[i-1][j][1];\n }else{\n prefix[i][val][1] = Math.max(prefix[i][val][1],1+prefix[i-1][j][1]);\n }\n }\n }\n\n // suffix\n suffix[n-1][nums[n-1]][0] = 1;\n suffix[n-1][nums[n-1]][1] = 1;\n for(int i=n-2;i>=0;i--){\n for(int j=1;j<128;j++){\n suffix[i][j][0] = suffix[i+1][j][0];\n suffix[i][j][1] = suffix[i+1][j][1];\n }\n suffix[i][nums[i]][0] = 1;\n if(suffix[i][nums[i]][1]==Integer.MAX_VALUE){\n suffix[i][nums[i]][1] = 1;\n }\n //prefix[i][nums[i]][1] = Math.max(prefix[i][nums[i]][1],1);\n \n for(int j=1;j<128;j++){\n if(suffix[i+1][j][0]==Integer.MAX_VALUE) continue;\n int val = j | nums[i];\n suffix[i][val][0] = Math.min(suffix[i][val][0],1+suffix[i+1][j][0]);\n if(suffix[i][val][1]==Integer.MAX_VALUE){\n suffix[i][val][1] = 1+suffix[i+1][j][1];\n }else{\n suffix[i][val][1] = Math.max(suffix[i][val][1],1+suffix[i+1][j][1]);\n }\n }\n }\n }\n}\n```
0
0
['Java']
0
find-the-maximum-sequence-value-of-array
Easy Java Solution
easy-java-solution-by-danish_jamil-d1jz
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
Danish_Jamil
NORMAL
2024-09-20T06:14:00.328203+00:00
2024-09-20T06:14:00.328226+00:00
23
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```java []\nclass Solution {\n private static final int MAX = 128;\n\n public int maxValue(int[] nums, int k) {\n boolean[][] dp = new boolean[nums.length][MAX];\n \n boolean[][] isMet = new boolean[MAX][k + 1];\n List<int[]> valid = new ArrayList<>();\n valid.add(new int[]{0, 0});\n isMet[0][0] = true;\n\n for (int i = nums.length - 1; i >= 0; --i) {\n List<int[]> nextValid = new ArrayList<>();\n for (int[] tmp : valid) {\n nextValid.add(tmp);\n if (tmp[1] + 1 <= k && !isMet[tmp[0] | nums[i]][tmp[1] + 1]) {\n isMet[tmp[0] | nums[i]][tmp[1] + 1] = true;\n nextValid.add(new int[]{tmp[0] | nums[i], tmp[1] + 1});\n }\n if (tmp[1] + 1 == k) {\n dp[i][tmp[0] | nums[i]] = true;\n }\n if (tmp[1] == k) {\n dp[i][tmp[0]] = true;\n }\n }\n valid = nextValid;\n }\n\n int result = 0;\n \n boolean[] isLeftMet = new boolean[MAX];\n isMet = new boolean[MAX][k + 1];\n valid = new ArrayList<>();\n valid.add(new int[]{0, 0});\n isMet[0][0] = true;\n\n for (int i = 0; i < nums.length; ++i) {\n List<int[]> nextValid = new ArrayList<>();\n for (int[] tmp : valid) {\n nextValid.add(tmp);\n if (tmp[1] + 1 <= k && !isMet[tmp[0] | nums[i]][tmp[1] + 1]) {\n isMet[tmp[0] | nums[i]][tmp[1] + 1] = true;\n nextValid.add(new int[]{tmp[0] | nums[i], tmp[1] + 1});\n }\n if (tmp[1] + 1 == k && !isLeftMet[tmp[0] | nums[i]] && i + 1 < nums.length) {\n int orResult = tmp[0] | nums[i];\n isLeftMet[orResult] = true;\n for (int j = 1; j < MAX; ++j) {\n if (dp[i + 1][j]) {\n result = Math.max(result, orResult ^ j);\n }\n }\n }\n }\n valid = nextValid;\n }\n \n return result;\n }\n}\n```
0
0
['Java']
0
find-the-maximum-sequence-value-of-array
C# | Dp solution
c-dp-solution-by-bora_marian-fpef
Intuition\ndp[i][j] = all the possible OR values computed till i if we choose j elements\nDp on left side ^ Dp on the right side to take k elements.\nDp on the
bora_marian
NORMAL
2024-09-20T05:32:55.135490+00:00
2024-09-20T05:36:37.824984+00:00
7
false
# Intuition\n$$dp[i][j]$$ = all the possible $$OR$$ values computed till $$i$$ if we choose $$j$$ elements\nDp on left side ^ Dp on the right side to take k elements.\nDp on the right side calculated by reversing nums array.\n\n# Code\n```csharp []\npublic class Solution {\n Dictionary<int, bool>[,] left;\n Dictionary<int, bool>[,] right;\n public int MaxValue(int[] nums, int k) \n {\n int n = nums.Length, result = 0;\n left = new Dictionary<int, bool>[n + 2, k + 2];\n right = new Dictionary<int, bool>[n + 2, k + 2];\n\n Dp(nums, k, left);\n Array.Reverse(nums, 0, nums.Length);\n Dp(nums, k, right);\n \n for (int i = k - 1; i + k < n; i++) \n {\n foreach(var lValue in left[i+1, k].Keys) \n {\n foreach(var rValue in right[n-1-i, k].Keys) \n {\n result = Math.Max(result, lValue ^ rValue);\n }\n }\n }\n \n return result;\n }\n public void Dp(int[] nums, int k, Dictionary<int, bool>[,] memo) \n {\n for (int i = 0; i <= nums.Length; i++) \n {\n memo[i, 0] = new Dictionary<int, bool>() {{0, true}}; \n }\n \n for (int i = 0; i < nums.Length; i++) \n { \n for (int j = 1; j <= k; j++) \n { \n if (j - 1 > i) continue;\n memo[i + 1, j] = new Dictionary<int, bool>(); \n foreach(var key in memo[i, j - 1].Keys) \n {\n memo[i + 1, j][key | nums[i]] = true;\n }\n if (j <= i) \n { \n //copy prev values\n foreach(var key in memo[i, j].Keys) \n {\n memo[i + 1, j][key] = true;\n }\n }\n }\n }\n }\n}\n```
0
0
['C#']
0
find-the-maximum-sequence-value-of-array
Python | Prefix + Suffix | O(128*nk + 128*128*n)
python-prefix-suffix-o128nk-128128n-by-a-xib7
Code\npython3 []\nfrom functools import lru_cache\nclass Solution:\n def maxValue(self, nums: List[int], k: int) -> int:\n n = len(nums)\n @cac
aryonbe
NORMAL
2024-09-20T05:21:42.332530+00:00
2024-09-20T05:21:42.332564+00:00
18
false
# Code\n```python3 []\nfrom functools import lru_cache\nclass Solution:\n def maxValue(self, nums: List[int], k: int) -> int:\n n = len(nums)\n @cache\n def dpLeft(i, k):\n if i < 0 or not k:\n return set()\n if k == 1:\n return set([nums[i]]) | dpLeft(i-1, k)\n prev = dpLeft(i-1, k-1)\n left = set()\n for mask in prev:\n left.add(mask | nums[i])\n return left | dpLeft(i-1, k)\n @cache\n def dpRight(i, k):\n if i >= n or not k: return set()\n if k == 1:\n return set([nums[i]]) | dpRight(i+1, k)\n nxt = dpRight(i+1, k-1)\n right = set()\n for mask in nxt:\n right.add(mask | nums[i])\n return right | dpRight(i+1, k)\n res = 0\n for i in range(1,n):\n for lmask in dpLeft(i-1,k):\n for rmask in dpRight(i,k):\n res = max(res, lmask ^ rmask)\n return res \n \n \n \n```
0
0
['Python3']
0
find-the-maximum-sequence-value-of-array
3d DP
3d-dp-by-nuk6-z2oq
\nclass Solution {\n public: int maxValue(vector < int > & a, int K) {\n int n = a.size();\n vector < vector < vector < unsigned long long >>> le(\n
nuk6
NORMAL
2024-09-18T20:56:20.497316+00:00
2024-09-18T20:56:20.497336+00:00
15
false
```\nclass Solution {\n public: int maxValue(vector < int > & a, int K) {\n int n = a.size();\n vector < vector < vector < unsigned long long >>> le(\n n, vector < vector < unsigned long long >> (K + 1, vector < unsigned long long > (129)));\n vector < vector < vector < unsigned long long >>> rt(\n n, vector < vector < unsigned long long >> (K + 1, vector < unsigned long long > (129)));\n for (int i = 0; i < n; ++i) {\n for (int k = 1; k <= min(i + 1, K); ++k) {\n for (int x = 0; x < 129; ++x) {\n if (k == 1) {\n le[i][1][x] = (a[i] == x) + ((i > 0) ? le[i - 1][1][x] : 0);\n } else {\n le[i][k][x] += le[i - 1][k][x];\n if ((x | a[i]) < 129)\n le[i][k][(x | a[i])] += le[i - 1][k - 1][x];\n }\n }\n }\n }\n reverse(a.begin(), a.end());\n for (int i = 0; i < n; ++i) {\n for (int k = 1; k <= min(i + 1, K); ++k) {\n for (int x = 0; x < 129; ++x) {\n if (k == 1) {\n rt[i][1][x] = (a[i] == x) + ((i > 0) ? rt[i - 1][1][x] : 0);\n } else {\n rt[i][k][x] += rt[i - 1][k][x];\n if ((x | a[i]) < 129)\n rt[i][k][(x | a[i])] += rt[i - 1][k - 1][x];\n }\n }\n }\n }\n int ans = 0;\n for (int i = K - 1; i + K < n; ++i) {\n for (int x = 0; x < 129; ++x) {\n for (int y = 0; y < 129; ++y) {\n if (le[i][K][x] && rt[n - i - 2][K][y]) {\n ans = max(ans, x ^ y);\n }\n }\n }\n }\n return ans;\n }\n};\n```
0
0
['Dynamic Programming']
0
find-the-maximum-sequence-value-of-array
Simple python3 solution | 1029 ms - faster than 96.88% solutions
simple-python3-solution-1029-ms-faster-t-36wc
Complexity\n- Time complexity: O(n\cdot k \cdot (n + k)) \n Add your time complexity here, e.g. O(n) \n\n- Space complexity: O(n^2\cdot k) \n Add your space com
tigprog
NORMAL
2024-09-18T11:48:37.018815+00:00
2024-09-18T11:48:37.018845+00:00
20
false
# Complexity\n- Time complexity: $$O(n\\cdot k \\cdot (n + k))$$ \n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n^2\\cdot k)$$ \n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\nwhere \n\n`n = nums.length <= 400`\n`m = max(nums[i]) < 2^7`\n\n# Code\n```python3 []\nclass Solution:\n def maxValue(self, nums: List[int], k: int) -> int:\n n = len(nums)\n\n suffix = []\n suffix_current = defaultdict(set)\n suffix_current[0].add(0)\n\n for i in range(n - k):\n elem = nums[-i - 1]\n for l in range(min(k - 1, i), -1, -1):\n suffix_current[l + 1].update(\n elem | value\n for value in suffix_current[l]\n )\n if i >= k - 1:\n suffix.append(suffix_current[k].copy())\n\n result = 0\n\n prefix_current = defaultdict(set)\n prefix_current[0].add(0)\n\n for i in range(n - k):\n elem = nums[i]\n for l in range(min(k - 1, i), -1, -1):\n prefix_current[l + 1].update(\n elem | value\n for value in prefix_current[l]\n )\n if i >= k - 1:\n current = max(\n a ^ b\n for a in suffix.pop()\n for b in prefix_current[k]\n )\n result = max(result, current)\n\n return result\n```
0
0
['Suffix Array', 'Prefix Sum', 'Python3']
0
find-the-maximum-sequence-value-of-array
Some sort of brute force
some-sort-of-brute-force-by-maxorgus-uykc
Key point:\n\nnumbers <=128\n\nso each subset we got by doing the bit manipulations could not be larger than 128 elements, a fairly comfortable upper limit for
MaxOrgus
NORMAL
2024-09-18T02:36:54.678450+00:00
2024-09-18T02:36:54.678492+00:00
23
false
Key point:\n\nnumbers <=128\n\nso each subset we got by doing the bit manipulations could not be larger than 128 elements, a fairly comfortable upper limit for such brute force loops to work\n\n# Code\n```python3 []\nclass Solution:\n def maxValue(self, nums: List[int], k: int) -> int:\n vals = {i:set([]) for i in range(k+1)}\n vals[0].add(0)\n dpl = []\n for a in nums:\n for t in range(k,0,-1):\n vals[t] = vals[t] | {a|b for b in vals[t-1]}\n dpl.append(vals[k])\n vals = {i:set([]) for i in range(k+1)}\n vals[0].add(0)\n dpr = []\n for a in nums[::-1]:\n for t in range(k,0,-1):\n vals[t] = vals[t] | {a|b for b in vals[t-1]}\n dpr.append(vals[k])\n N = len(nums)\n dpr = dpr[::-1]\n res = 0\n for i in range(N-1):\n lset = dpl[i]\n rset = dpr[i+1]\n for a in lset:\n for b in rset:\n res = max(res,a^b)\n return res\n\n \n```
0
0
['Python3']
0
find-the-maximum-sequence-value-of-array
JAVA
java-by-abhiguptanitb-lcvr
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
abhiguptanitb
NORMAL
2024-09-18T01:39:52.792075+00:00
2024-09-18T01:39:52.792099+00:00
4
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```java []\nclass Solution {\n public int maxValue(int[] nums, int k) {\n \n int n = nums.length;\n boolean dp[][][] = new boolean[n][k+2][1 << 7+1];\n\n dp[0][1][nums[0]] = true;\n \n for(int i = 1; i < n; i++) {\n dp[i][1][nums[i]] = true;\n for(int j = 1; j <= 128; j++) {\n for(int a = 1; a <= k; a++) {\n if ( dp[i-1][a][j] ) {\n dp[i][a+1][j|nums[i]] = true;\n dp[i][a][j] = true;\n }\n }\n }\n }\n\n boolean dp2[][][] = new boolean[n][k+2][1 << 7+1];\n dp2[n-1][1][nums[n-1]] = true;\n \n for(int i = n-2; i >= 0; i--) {\n dp2[i][1][nums[i]] = true;\n for(int j = 1; j <= 128; j++) {\n for(int a = 1; a <= k; a++) {\n if ( dp2[i+1][a][j]) {\n dp2[i][a+1][j|nums[i]] = true;\n dp2[i][a][j] = true;\n }\n }\n }\n }\n\n int max = 0;\n for(int i = 0; i < n; i++) {\n if ( i+1 >= k && n-(i+1) >= k) {\n for(int a = 1; a <= 128; a++) {\n for(int b = 1; b <= 128; b++) {\n if ( dp[i][k][a] && dp2[i+1][k][b] ) {\n max = Math.max(max, a^b);\n }\n \n }\n }\n }\n } \n return max;\n }\n}\n```
0
0
['Java']
0
find-the-maximum-sequence-value-of-array
C++ Solution | 3D - DP | Bitmasking
c-solution-3d-dp-bitmasking-by-manaspara-rxg8
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
manasparasar
NORMAL
2024-09-17T00:32:02.991211+00:00
2024-09-17T00:32:26.268038+00:00
56
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n vector<vector<vector<int>>> func(int n, int k, vector<int>& nums){\n vector<vector<vector<int>>> dp(n, vector<vector<int>>(k+1, vector<int>(128, 0)));\n dp[0][0][0] = 1;\n for(int i=0; i<n; i++)\n dp[i][0][0] = 1;\n dp[0][1][nums[0]] = 1;\n\n for(int i=1; i<n; i++){\n for(int j=1; j<=k; j++){\n for(int l=0; l<128; l++){\n dp[i][j][l] |= dp[i-1][j][l];\n dp[i][j][nums[i] | l] |= dp[i-1][j-1][l];\n }\n }\n }\n\n return dp; \n }\n int maxValue(vector<int>& nums, int k) {\n int n = nums.size();\n vector<vector<vector<int>>> left = func(n, k, nums);\n reverse(begin(nums), end(nums));\n vector<vector<vector<int>>> right = func(n, k, nums);\n int res = 0;\n for (int i = k - 1; i + k < nums.size(); i++) {\n for (int a = 0; a < 128; a++) {\n for (int b = 0; b < 128; b++) {\n if (left[i][k][a] && right[n-i-2][k][b]) {\n res = max(res, a ^ b);\n }\n }\n }\n }\n return res;\n }\n};\n```
0
0
['C++']
1
find-the-maximum-sequence-value-of-array
Easy python solution
easy-python-solution-by-fredrick_li-ycfu
Code\npython3 []\nclass Solution:\n def maxValue(self, nums: List[int], k: int) -> int:\n m = max(nums)\n l = len(bin(m)) - 2\n n = len(
Fredrick_LI
NORMAL
2024-09-16T14:42:28.613203+00:00
2024-09-16T14:42:28.613242+00:00
24
false
# Code\n```python3 []\nclass Solution:\n def maxValue(self, nums: List[int], k: int) -> int:\n m = max(nums)\n l = len(bin(m)) - 2\n n = len(nums)\n\n right = [-1] * (1 << l)\n reached = {0: 0}\n count = {mask:0 for mask in range(1 << l)}\n for ind in range(n-1,-1,-1):\n num = nums[ind]\n \n newReached = dict(reached)\n for mask in reached:\n if reached[mask] < k:\n newMask = mask | num\n if newMask not in newReached:\n newReached[newMask] = reached[mask] + 1\n else:\n newReached[newMask] = min(reached[mask] + 1, newReached[newMask])\n reached = newReached\n\n for mask in list(count.keys()):\n if mask | num == mask:\n count[mask] += 1\n if count[mask] >= k and mask in reached:\n del count[mask]\n right[mask] = ind\n \n left = {}\n reached = {0: 0}\n count = {mask:0 for mask in range(1 << l)}\n for ind in range(n):\n num = nums[ind]\n \n newReached = dict(reached)\n for mask in reached:\n if reached[mask] < k:\n newMask = mask | num\n if newMask not in newReached:\n newReached[newMask] = reached[mask] + 1\n else:\n newReached[newMask] = min(reached[mask] + 1, newReached[newMask])\n reached = newReached\n\n for mask in list(count.keys()):\n if mask | num == mask:\n count[mask] += 1\n if count[mask] >= k and mask in reached:\n del count[mask]\n left[mask] = ind\n \n for mask in range((1 << l) - 1, -1, -1):\n for l in left:\n if left[l] < right[l ^ mask]:\n return mask\n\n\n```
0
0
['Python3']
0
find-the-maximum-sequence-value-of-array
Java | with comments in code | Find all possible ORs
java-with-comments-in-code-find-all-poss-3rq4
Intuition\n Describe your first thoughts on how to solve this problem. \nFor each index, find all possible OR, with the elements :-\n-> from start, till that in
Ayush-Vardhan-03
NORMAL
2024-09-16T14:02:25.444655+00:00
2024-09-16T14:02:25.444681+00:00
42
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nFor each index, find all possible OR, with the elements :-\n-> from start, till that index\n-> from end, till that index\nThen take XOR of all left-OR and right-OR\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- Create 3D array, where :-\n - 1st dimension -> index of nums\n - 2nd dimension -> possible values of OR (max-128)\n - 3rd dimension -> of size 2\n - [0]= Minimum count of elements required to make that OR-value\n - [1]= Maximum count of elements that can be included to make that OR-value\n- Make 2 such arrays, for storing count of elements, at each index, to make each possible OR-value\n - $$lftOR$$ for storing count from starting of nums till any index\n - $$rgtOR$$ for storing count from end of nums till any index\n- Approach to make all possible OR :-\n - At 1st-index, only one OR-value can be made (take that element)\n - At 2nd-index, we have two choices; first: take curr-element alone; second: take OR of curr-element with the value at index-1\n - At 3rd-index, we will again do same, take OR of curr-element with all the possible OR-values at previous index\n - That\'s how we will build both arrays; $$lftOR$$ from starting index and $$rgtOR$$ from ending index\n- But there is one more thing, we cannot just take OR of current-element with every possible OR-value from previous index, becasue we can only choose $$k$$ elements.\n- That\'s why there is a need to take count of minimum elements needed to make the OR-value. So that we can check before taking OR, that min-count of elements of OR-value is smaller than $$k$$ and greater than $$0$$ or not.\n- And if after taking OR of curr-element with previous OR, the value came was already been made by some other elements, then we will only increment the maximum elements (means [1]-index in the array)\n- In the end after building both arrays, we will iterate at each index, and through each possible OR-value whose maximum count of elements is greater than or equal to $$k$$\n- At each index-$$i$$, we will take possible OR-values from $$lftOR[i-1]$$ and $$rgtOR[i]$$, and XOR them, and update the $$ans$$ with maximum value.\n\n# Complexity\n- Time complexity: O (n * 128 * 128)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O (2 * n * 128 * 2)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```java []\nclass Solution {\n public int maxValue(int[] nums, int k) {\n int n = nums.length;\n int ans = 0;\n /*\n find all possible OR at each index, from left and right,\n and store the count of elements that made that OR,\n We can do that because max OR we can have is 128\n */\n int[][][] lftOR = new int[n][128][2];\n int[][][] rgtOR = new int[n][128][2];\n /*\n [0] -> minimum count of nums needed to make that OR\n [1] -> maximum count of nums we can take to make that OR\n */\n lftOR[0][nums[0]][0] = lftOR[0][nums[0]][1] = 1;//first left element\n rgtOR[n-1][nums[n-1]][0] = rgtOR[n-1][nums[n-1]][1] = 1;//first right element\n\n // \'l\'-> index for left array, \'r\'-> index for right array\n for (int l=1, r=n-2; l < n-k; l++, r--) {\n /*\n we will iterate OR value in decreasing manner,\n because taking OR, may only increase num\'s value,\n so first we will copy count of OR, from previous index,\n and then update, if possible\n */\n for (int or=127; or > 0; or--) {\n // New-OR can only be made by taking OR with previous-ORs\n // Means min-count at previous index must be greater than zero\n if (lftOR[l-1][or][0] > 0) {\n lftOR[l][or] = Arrays.copyOf(lftOR[l-1][or], 2);\n /*\n if min-count of nums needed to make curr-OR is less than K,\n only then we can OR; current-num and current-OR\n */\n if (lftOR[l][or][0] < k) update(lftOR[l], or, or|nums[l]);\n }\n // Same we will do for right array\n if (rgtOR[r+1][or][0] > 0) {\n rgtOR[r][or] = Arrays.copyOf(rgtOR[r+1][or], 2);\n\n if (rgtOR[r][or][0] < k) update(rgtOR[r], or, or|nums[r]);\n }\n }\n // if current num taken alone\n update(lftOR[l], 0, nums[l]);\n update(rgtOR[r], 0, nums[r]);\n }\n\n // at each index, XOR all possible combinations of OR from left-1 and right\n for (int i=k; i<=n-k; i++) {\n /*\n if cnt of max-nums, that can make up curr-OR is less than K,\n then we can\'t take that OR, so we will continue\n */\n for (int lft=1; lft < 128; lft++) {\n if (lftOR[i-1][lft][1] < k) continue;\n\n for (int rgt=1; rgt < 128; rgt++) {\n if (rgtOR[i][rgt][1] < k) continue;\n \n ans = Math.max(ans, lft ^ rgt);//Take XOR of only valid ORs\n }\n }\n }\n\n return ans;\n }\n\n void update(int[][] arr, int less, int more) {\n if (arr[more][0] == 0) { // if this OR is appearing first time\n arr[more][0] = arr[less][0] +1;\n arr[more][1] = arr[less][1] +1;\n } else { // otherwise update\n arr[more][0] = Math.min(arr[more][0], arr[less][0]+1);\n arr[more][1] = Math.max(arr[more][1], arr[less][1]+1);\n }\n }\n}\n```
0
0
['Java']
0
find-the-maximum-sequence-value-of-array
Beat 100% user
beat-100-user-by-tranxuanbaoviet-8ay1
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
tranxuanbaoviet
NORMAL
2024-09-16T13:59:13.635262+00:00
2024-09-16T13:59:13.635295+00:00
20
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```python []\nclass Solution(object):\n def maxValue(self, nums, k):\n """\n :type nums: List[int]\n :type k: int\n :rtype: int\n """\n n = len(nums)\n \n # Initialize prefix_OR\n # prefix_OR[i][j] is the set of ORs achievable by selecting j elements from first i elements\n prefix_OR = [ [set() for _ in range(k+1)] for _ in range(n+1)]\n prefix_OR[0][0].add(0)\n \n for i in range(1, n+1):\n num = nums[i-1]\n for j in range(0, k+1):\n # First, carry over the previous ORs\n prefix_OR[i][j].update(prefix_OR[i-1][j])\n # Then, if we can select this element\n if j > 0:\n for s in prefix_OR[i-1][j-1]:\n prefix_OR[i][j].add(s | num)\n \n # Initialize suffix_OR\n # suffix_OR[i][j] is the set of ORs achievable by selecting j elements from last n - i elements\n suffix_OR = [ [set() for _ in range(k+1)] for _ in range(n+1)]\n suffix_OR[n][0].add(0)\n \n for i in range(n-1, -1, -1):\n num = nums[i]\n for j in range(0, k+1):\n # First, carry over the previous ORs\n suffix_OR[i][j].update(suffix_OR[i+1][j])\n # Then, if we can select this element\n if j > 0:\n for s in suffix_OR[i+1][j-1]:\n suffix_OR[i][j].add(s | num)\n \n max_xor = 0\n # Iterate over all possible split points\n # We need at least k elements on the left and k on the right\n for i in range(k, n - k +1):\n # Get all possible ORs for the first k elements from first i elements\n left_ORs = prefix_OR[i][k]\n # Get all possible ORs for the last k elements from last n - i elements\n right_ORs = suffix_OR[i][k]\n # Compute the maximum XOR between any pair from left_ORs and right_ORs\n for or1 in left_ORs:\n # To optimize, iterate through right_ORs and compute or1 ^ or2\n # Keep track of the maximum\n for or2 in right_ORs:\n current_xor = or1 ^ or2\n if current_xor > max_xor:\n max_xor = current_xor\n # Early exit if maximum possible XOR is achieved\n if max_xor == 127: # since nums[i] < 128\n return max_xor\n return max_xor\n\n \n```
0
0
['Python']
0
find-the-maximum-sequence-value-of-array
3D DP solution
3d-dp-solution-by-andreashzz-ad7s
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
AndreasHzz
NORMAL
2024-09-15T13:45:17.280873+00:00
2024-09-15T13:45:17.280901+00:00
38
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```java []\nclass Solution {\n boolean[][][] dp;\n boolean[][][] dp1;\n public int maxValue(int[] nums, int k) {\n dp = new boolean[nums.length-k][128][k+2];\n dp1 = new boolean[nums.length-k][128][k+2];\n dp[0][nums[0]][1]=true;\n dp[0][0][0]=true;\n //System.out.println(dp[0][2][1]);\n for(int i = 1; i<nums.length-k; i++){\n int cur = nums[i];\n for(int j = 0; j<128; j++){\n for(int x = 0; x<=Math.min(k,i); x++){\n if(dp[i-1][j][x])dp[i][j][x]=dp[i-1][j][x];\n if(dp[i-1][j][x] && x+1<=k){\n dp[i][j|cur][x+1]=true;\n //if(i==2 && j==4 && cur==5 && x==1)System.out.println(dp[i][j|cur][x+1]);\n }\n }\n }\n }\n for(int i = 0; i<nums.length-k; i++){\n for(int j = 0; j<128; j++){\n if(dp[i][j][2])System.out.println(j);\n }\n }\n dp1[0][nums[nums.length-1]][1]=true;\n dp1[0][0][0]=true;\n \n for(int i = nums.length-2; i>=k; i--){\n int cur = nums[i];\n int index = nums.length-1-i;\n for(int j = 0; j<128; j++){\n for(int x = 0; x<=Math.min(k,index); x++){\n if(dp1[index-1][j][x])dp1[index][j][x]=dp1[index-1][j][x];\n if(dp1[index-1][j][x] && x+1<=k){\n dp1[index][j|cur][x+1]=true;\n }\n }\n }\n }\n \n int res = 0;\n for(int i = k-1; i<nums.length-k; i++){\n for(int j = 0; j<128; j++){\n if(dp[i][j][k]){\n int left = nums.length-2-i;\n for(int x = 0; x<128; x++){\n if(dp1[left][x][k]){\n \n res = Math.max(res, j^x);\n }\n }\n }\n }\n }\n return res;\n \n }\n}\n```
0
0
['Java']
0
find-the-maximum-sequence-value-of-array
Cpp STL no DP plain bits concept
cpp-stl-no-dp-plain-bits-concept-by-user-vtca
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
user7634ri
NORMAL
2024-09-15T13:25:30.836227+00:00
2024-09-15T13:25:30.836253+00:00
44
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n int maxValue(vector<int>& nums, int k) {\n unordered_set<int> pref[nums.size() + 1];\n unordered_set<int> poss[k + 1];\n poss[1] = {};\n\n for(int i = 0; i < nums.size() - k; i ++) {\n\n unordered_set<int> sopp1[k + 1];\n \n for(int j = 2; j <= min(k, i + 1); j ++) {\n for(auto &it: poss[j - 1]) {\n sopp1[j].insert(it | nums[i]);\n }\n }\n\n sopp1[1].insert(nums[i]);\n for(int j = 0; j <= k;j ++) {\n for(auto it: sopp1[j]) {\n poss[j].insert(it);\n }\n }\n\n for(auto &it: poss[k]) {\n if(i > 0) {\n for(auto kl: pref[i - 1]) {\n pref[i].insert(kl);\n }\n }\n pref[i].insert(it); // possible ors\n }\n }\n\n unordered_set<int> sopp[k + 1];\n\n int ans = 0;\n for(int i = nums.size() - 1; i >= k; i --) {\n \n int stop = nums.size() - i;\n unordered_set<int> sopp1[k + 1];\n for(int j = 2; j <= min(k, stop); j ++) {\n for(auto &it: sopp[j - 1]) {\n sopp1[j].insert(it | nums[i]);\n }\n }\n\n sopp1[1].insert(nums[i]);\n for(int j = 0; j <= k;j ++) {\n for(auto it: sopp1[j]) {\n sopp[j].insert(it);\n }\n }\n\n int pivot = nums.size() - k;\n pivot = min(pivot, i - 1);\n\n unordered_set<int> pref_ors = pref[pivot];\n \n for(auto &it: sopp[k]) {\n for(auto &jt: pref_ors) {\n ans = max(ans, it ^ jt);\n }\n }\n }\n return ans;\n }\n};\n```
0
0
['C++']
0
find-the-maximum-sequence-value-of-array
DP + Bitset Optimization (Knapsack) || Easy to understand || Beats 50% || CPP
dp-bitset-optimization-knapsack-easy-to-br3wx
Complexity\n- Time complexity:O(n * k * 2^7 + k^2 * 2^7)\n Add your time complexity here, e.g. O(n) \n\n- Space complexity:O(n * k * 2^7)\n Add your space compl
dubeyad2003
NORMAL
2024-09-15T12:43:27.376412+00:00
2024-09-15T12:43:27.376437+00:00
76
false
# Complexity\n- Time complexity:$$O(n * k * 2^7 + k^2 * 2^7)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:$$O(n * k * 2^7)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n int maxValue(vector<int>& nums, int k) {\n int n = nums.size();\n vector<vector<bitset<128>>> pd(n+1, vector<bitset<128>>(k+1, bitset<128>()));\n vector<vector<bitset<128>>> sd(n+1, vector<bitset<128>>(k+1, bitset<128>()));\n for(int i=0; i<=n; i++) pd[i][0][0] = sd[i][0][0] = 1;\n for(int l=1; l<=k; l++){\n for(int i=1; i<=n; i++){\n pd[i][l] |= pd[i-1][l];\n for(int j=0; j<128; j++){\n if(pd[i-1][l-1][j]) pd[i][l][j | nums[i-1]] = 1; \n }\n }\n for(int i=n-1; i>=0; i--){\n sd[i][l] |= sd[i+1][l];\n for(int j=0; j<128; j++){\n if(sd[i+1][l-1][j]) sd[i][l][j | nums[i]] = 1;\n }\n }\n }\n int maxi = 0;\n for(int i=k; i<=n-k; i++){\n for(int j=0; j<128; j++){\n for(int l=0; l<128; l++){\n if(pd[i][k][j] && sd[i][k][l]) maxi = max(maxi, j ^ l);\n }\n }\n }\n return maxi;\n }\n};\n```
0
0
['C++']
0
find-the-maximum-sequence-value-of-array
Java | DP
java-dp-by-divyanshugd48-plqj
Intuition\n Describe your first thoughts on how to solve this problem. \nSince the contraints are small, so the first idea was DP. And we need to generate all t
divyanshugd48
NORMAL
2024-09-15T12:15:20.546981+00:00
2024-09-15T12:15:20.547014+00:00
29
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nSince the contraints are small, so the first idea was DP. And we need to generate all the possible combination, so I used it. Rest are given below.\n\nPS: Solution beats 100% in terms of Time as well as Memory.\n\n\n# Approach\n1. Generate all the possible numbers using OR operation present in the given array.\n2. Store the index of all the subsequences of length k which are obtained through OR operation.\n3. Doing step 2 from LtoR and RtoL. Since we need to divide overall subsequence into 2 of each size k.\n4. Now, we have to take max XOR of all the possible combinations obtained from doing OR operation. since the maximum possible number be less than 2^7 which is 127.\n5. We can check using idx1 for LtoR and idx2 for RtoL to avoid overlapping between 2 region of subsequences.\n\n# Complexity\n- Time complexity: `O(n * k * 2^k)`\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: `O(n * k * 2^k)`\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n\n# Code\n```java []\nclass Solution {\n\n private int[][][] dp1, dp2;\n private int[] idx1, idx2;\n\n public void solvef(int i, int curr, int cnt, int[] nums) {\n if (cnt == 0) {\n idx1[curr] = Math.min(idx1[curr], i - 1);\n return;\n }\n if (i >= nums.length)\n return;\n if (dp1[i][curr][cnt] == 1)\n return;\n dp1[i][curr][cnt] = 1;\n solvef(i + 1, (curr | nums[i]), cnt - 1, nums);\n solvef(i + 1, curr, cnt, nums);\n return;\n }\n\n public void solveb(int i, int curr, int cnt, int[] nums) {\n if (cnt == 0) {\n idx2[curr] = Math.max(idx2[curr], i + 1);\n return;\n }\n if (i < 0)\n return;\n if (dp2[i][curr][cnt] == 1)\n return;\n dp2[i][curr][cnt] = 1;\n solveb(i - 1, (curr | nums[i]), cnt - 1, nums);\n solveb(i - 1, curr, cnt, nums);\n return;\n }\n\n public int maxValue(int[] nums, int k) {\n int n = nums.length;\n dp1 = new int[n][128][k + 1];\n dp2 = new int[n][128][k + 1];\n idx1 = new int[128];\n idx2 = new int[128];\n for (int i = 0; i < 128; i++) {\n idx1[i] = n;\n idx2[128 - i - 1] = -1;\n }\n solvef(0, 0, k, nums);\n solveb(n - 1, 0, k, nums);\n int res = 0;\n for (int i = 0; i < 128; i++) {\n for (int j = 0; j < 128; j++) {\n if (idx1[i] < idx2[j])\n res = Math.max(res, (i ^ j));\n }\n }\n return res;\n }\n}\n```
0
0
['Java']
0
find-the-maximum-sequence-value-of-array
Simple solution with comments
simple-solution-with-comments-by-snj07-b2q2
java\nclass Solution {\n public int maxValue(int[] nums, int k) {\n int n = nums.length; // Length of the input array\n final int MAX_OR = 1<<
snj07
NORMAL
2024-09-15T10:28:47.837183+00:00
2024-09-15T10:28:47.837225+00:00
56
false
```java\nclass Solution {\n public int maxValue(int[] nums, int k) {\n int n = nums.length; // Length of the input array\n final int MAX_OR = 1<<7; // Max possible OR result (2^7 ) as we have 1 <= nums[i] < 2^7\n\n // \'pre\' stores if it\'s possible to get an OR result `u` using a subsequence\n // of length `h` from the first `i` elements.\n boolean[][][] pre = new boolean[n + 1][k + 1][MAX_OR];\n\n // \'suf\' stores if it\'s possible to get an OR result `u` using a subsequence\n // of length `h` from the elements after index `i`.\n boolean[][][] suf = new boolean[n + 1][k + 1][MAX_OR];\n\n // Initialize the base case for `pre`: It\'s possible to get an OR result of 0 with 0 elements.\n pre[0][0][0] = true;\n\n // Fill the \'pre\' table (from left to right)\n for (int i = 0; i < n; i++) {\n int currentNum = nums[i]; // Current element in the array\n for (int subsequenceLength = 0; subsequenceLength <= k; subsequenceLength++) {\n for (int orValue = 0; orValue < MAX_OR; orValue++) {\n // If it\'s possible to form a subsequence of length `subsequenceLength`\n // with OR value `orValue` up to index `i`\n if (pre[i][subsequenceLength][orValue]) {\n // Option 1: Do not include nums[i] in the subsequence\n pre[i + 1][subsequenceLength][orValue] = true;\n \n // Option 2: Include nums[i] in the subsequence\n if (subsequenceLength < k) {\n pre[i + 1][subsequenceLength + 1][orValue | currentNum] = true;\n }\n }\n }\n }\n }\n\n // Initialize the base case for `suf`: It\'s possible to get an OR result of 0 with 0 elements.\n suf[n][0][0] = true;\n\n // Fill the \'suf\' table (from right to left)\n for (int i = n - 1; i >= 0; i--) {\n int currentNum = nums[i]; // Current element in the array\n for (int subsequenceLength = 0; subsequenceLength <= k; subsequenceLength++) {\n for (int orValue = 0; orValue < MAX_OR; orValue++) {\n // If it\'s possible to form a subsequence of length `subsequenceLength`\n // with OR value `orValue` starting from index `i + 1`\n if (suf[i + 1][subsequenceLength][orValue]) {\n // Option 1: Do not include nums[i] in the subsequence\n suf[i][subsequenceLength][orValue] = true;\n \n // Option 2: Include nums[i] in the subsequence\n if (subsequenceLength < k) {\n suf[i][subsequenceLength + 1][orValue | currentNum] = true;\n }\n }\n }\n }\n }\n\n // Variable to store the maximum XOR result\n int maxXorValue = 0;\n\n // Iterate through possible split points where the left and right subsequences meet\n for (int splitIndex = k - 1; splitIndex <= n - 1 - k; splitIndex++) {\n for (int leftOrValue = 0; leftOrValue < MAX_OR; leftOrValue++) {\n // Check if it\'s possible to have a subsequence of length k from the left side\n if (!pre[splitIndex + 1][k][leftOrValue]) {\n continue; // Skip if not possible\n }\n \n for (int rightOrValue = 0; rightOrValue < MAX_OR; rightOrValue++) {\n // Check if it\'s possible to have a subsequence of length k from the right side\n if (!suf[splitIndex + 1][k][rightOrValue]) {\n continue; // Skip if not possible\n }\n\n // Compute the XOR of the OR values from the left and right subsequences\n maxXorValue = Math.max(maxXorValue, leftOrValue ^ rightOrValue);\n }\n }\n }\n return maxXorValue; // Return the maximum XOR value found\n }\n}\n\n\n```
0
0
['Bit Manipulation', 'Prefix Sum', 'Java']
0
find-the-maximum-sequence-value-of-array
Go solution
go-solution-by-fvadev-t38y
Intuition\n\n Describe your first thoughts on how to solve this problem. \nBy the limitaion - each value is less than 128. So it is make an idea to use set/hash
fvadev
NORMAL
2024-09-15T09:41:39.379505+00:00
2024-09-15T09:41:39.379537+00:00
13
false
# Intuition\n\n<!-- Describe your first thoughts on how to solve this problem. -->\nBy the limitaion - each value is less than 128. So it is make an idea to use set/hash some how.\n\nAnother part of problem - the subsequence should be the same order it may lead to thin about prefixes.\n\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\nSo, solution uses left and right prefix of OR subsequences. So `prefixLeft[i]` stores flags for all possable 127 variants that are exists in combinations of k elements left from index. The same idea for `prefixRight`. \n\nFor preparing `prefix(Left|Right)` slices `dp(Left|Right)` are used. These slices store information about all possible subset from k elements. So for some position `i` on the string `dpLeft[j]` - stores all possible subsets from k-elements which till the `i`-th letter in the string. The same idea for `dpRight[j]` but it stores subsets from the tail to `len(s)-i` position.\n\nIt is possible to use map instead of `[128]bool` here, but seems it will be slower.\n\n# Complexity\n- Time complexity:\n- $$O(n*k)$$, n - length of array \n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n- $$O(n)$$, n - length of array \n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```golang []\nfunc maxValue(nums []int, k int) int {\n\tn := len(nums)\n\n\tprefixLeft, dpLeft := newPrefix(n), newPrefix(k)\n\tprefixRight, dpRight := newPrefix(n), newPrefix(k)\n\tfor i, val := range nums {\n\t\tfor j := k; j > 0; j-- {\n\t\t\tdpLeft.add(j, val)\n\t\t\tdpRight.add(j, nums[n-1-i])\n prefixLeft.set(i+1, dpLeft.get(k))\n prefixRight.set(i+1, dpRight.get(k))\n\t\t}\n\t}\n\n\tresult := 0\n\tfor i := k; i < n-k+1; i++ {\n\t\tfor left, ok1 := range prefixLeft.data[i] {\n\t\t\tfor right, ok2 := range prefixRight.data[n-i] {\n\t\t\t\tif ok1 && ok2 {\n\t\t\t\t\tresult = max(result, left^right)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn result\n}\n\nconst maxVal = 128\n\ntype setSubsequences = [maxVal]bool\n\ntype prefix struct {\n\tdata []setSubsequences\n}\n\nfunc newPrefix(n int) *prefix {\n\tdata := make([]setSubsequences, n+1)\n data[0][0] = true // allow to add each elements to subset[1]\n\treturn &prefix{data: data}\n}\n\nfunc (p *prefix) get(k int) setSubsequences {\n\treturn p.data[k]\n}\n\nfunc (p *prefix) add(j int, val int) {\n\tfor x := 0; x < maxVal; x++ {\n\t\tif p.data[j-1][x] {\n\t\t\tp.data[j][x|val] = true\n\t\t}\n\t}\n}\n\nfunc (p *prefix) set(j int, set setSubsequences) {\n\tfor key, ok := range set {\n p.data[j][key] = ok\n }\n}\n```
0
0
['Go']
0
find-the-maximum-sequence-value-of-array
BEST PYTHON SOLUTION WITH 3988MS OF RUNTIME !
best-python-solution-with-3988ms-of-runt-w3cb
\n# Code\npython3 []\nfrom typing import List\nfrom collections import defaultdict\nfrom math import inf\n\nclass Solution:\n def maxValue(self, arr: List[in
rishabnotfound
NORMAL
2024-09-15T09:32:48.561938+00:00
2024-09-15T09:32:48.561989+00:00
24
false
\n# Code\n```python3 []\nfrom typing import List\nfrom collections import defaultdict\nfrom math import inf\n\nclass Solution:\n def maxValue(self, arr: List[int], maxCnt: int) -> int:\n n = len(arr)\n\n def calcConfigs(elems: List[int]):\n states = {(0, 0)}\n stateMap = defaultdict(lambda: -1)\n \n for i, num in enumerate(elems):\n newStates = set()\n for cnt, mask in states:\n if cnt < maxCnt:\n newStates.add((cnt + 1, mask | num))\n if cnt + 1 == maxCnt and (mask | num) not in stateMap:\n stateMap[mask | num] = i + 1\n states |= newStates # Merge new states\n return stateMap\n\n # Forward and reverse configurations\n forward = calcConfigs(arr)\n reverse = calcConfigs(arr[::-1])\n\n res = -inf\n\n # Compare forward and reverse bitmasks\n for mask1, pos1 in forward.items():\n for mask2, pos2 in reverse.items():\n if pos1 + pos2 <= n:\n res = max(res, mask1 ^ mask2)\n \n return res\n\n```
0
0
['Python3']
0
find-the-maximum-sequence-value-of-array
My Solution
my-solution-by-hope_ma-51w6
\n/**\n * Time Complexity: O((n - k) * masks * (k + masks))\n * Space Complexity: O((n - k) * k * masks)\n * where `n` is the length of the vector `nums`\n *
hope_ma
NORMAL
2024-09-15T08:58:18.179638+00:00
2024-09-15T08:58:18.179662+00:00
0
false
```\n/**\n * Time Complexity: O((n - k) * masks * (k + masks))\n * Space Complexity: O((n - k) * k * masks)\n * where `n` is the length of the vector `nums`\n * `masks` is O(2 ^ 7)\n */\nclass Solution {\n public:\n int maxValue(const vector<int> &nums, const int k) {\n const int max_num = *max_element(nums.begin(), nums.end());\n const int bits = get_bits(max_num);\n const int masks = 1 << bits;\n const int n = static_cast<int>(nums.size());\n bool left[n - k + 1][k][masks];\n memset(left, 0, sizeof(left));\n for (int i = 1; i < n - k + 1; ++i) {\n for (int j = 1; j < min(i, k) + 1; ++j) {\n for (int m = 0; m < masks; ++m) {\n left[i][j - 1][m] = left[i - 1][j - 1][m];\n }\n if (j == 1) {\n left[i][j - 1][nums[i - 1]] = true;\n } else {\n // j > 1\n for (int m = 0; m < masks; ++m) {\n if (left[i - 1][j - 2][m]) {\n left[i][j - 1][m | nums[i - 1]] = true;\n }\n }\n }\n }\n }\n \n bool right[n - k + 1][k][masks];\n memset(right, 0, sizeof(right));\n for (int i = n - 1; i > k - 1; --i) {\n for (int j = 1; j < min(n - i, k) + 1; ++j) {\n for (int m = 0; m < masks; ++m) {\n right[i - k][j - 1][m] = right[i + 1 - k][j - 1][m];\n }\n if (j == 1) {\n right[i - k][j - 1][nums[i]] = true;\n } else {\n // j > 1\n for (int m = 0; m < masks; ++m) {\n if (right[i + 1 - k][j - 2][m]) {\n right[i - k][j - 1][m | nums[i]] = true;\n }\n }\n }\n }\n }\n \n int ret = 0;\n for (int i = k - 1; i < n - k; ++i) {\n for (int lm = 0; lm < masks; ++lm) {\n if (!left[i + 1][k - 1][lm]) {\n continue;\n }\n \n for (int rm = 0; rm < masks; ++rm) {\n if (right[i + 1 - k][k - 1][rm]) {\n ret = max(ret, lm ^ rm);\n }\n }\n }\n }\n return ret;\n }\n \n private:\n int get_bits(const int num) {\n int ret = 0;\n for (int number = num; number > 0; number >>= 1) {\n ++ret;\n }\n return ret;\n }\n};\n```
0
0
[]
0
find-the-maximum-sequence-value-of-array
Submask's of a mask (DP approach)
submasks-of-a-mask-dp-approach-by-dnitin-o5vi
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \nSubmask\'s of a mask an
gyrFalcon__
NORMAL
2024-09-15T07:54:41.889910+00:00
2024-09-15T07:54:41.889941+00:00
63
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nSubmask\'s of a mask and DP approach (thinking in brute force way)\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO((n * k * (3 ^ 7)) + ((4 ^ 7) * n)) that\'s approx less than O((n * k * (3 ^ 7)) / 2)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO((n * k * (3 ^ 7)) / 32)\n\n# Code\n```cpp []\nclass Solution {\npublic:\n int maxValue(vector<int>& num, int k) {\n int n = num.size();\n bool dpPref[n][(1<<7)][k+1];\n bool dpSuff[n][(1<<7)][k+1];\n for(int i=0;i<n;i++){\n for(int j=0;j<(1<<7);j++){\n for(int l=0;l<=k;l++){\n dpPref[i][j][l] = false;\n dpSuff[i][j][l] = false;\n }\n }\n }\n dpPref[0][num[0]][1] = true;\n dpPref[0][0][0] = true;\n for(int i=1;i<n;i++){\n dpPref[i][num[i]][1] = true;\n dpPref[i][0][0] = true;\n for(int mask=0;mask<(1<<7);mask++){\n for(int len=1;len<=k;len++){\n dpPref[i][mask][len] = (dpPref[i][mask][len] | dpPref[i-1][mask][len]);\n }\n for(int s=mask;s;s=(s-1)&mask){\n if(mask != (s | num[i])) continue;\n for(int len=1;len<=k;len++){\n dpPref[i][mask][len] = (dpPref[i][mask][len] | dpPref[i-1][s][len - 1]);\n }\n }\n }\n }\n \n dpSuff[n-1][num[n-1]][1] = true;\n dpSuff[n-1][0][0] = true;\n for(int i=n-2;i>=0;i--){\n dpSuff[i][num[i]][1] = true;\n dpSuff[i][0][0] = true;\n for(int mask=0;mask<(1<<7);mask++){\n for(int len=1;len<=k;len++){\n dpSuff[i][mask][len] = (dpSuff[i][mask][len] | dpSuff[i+1][mask][len]);\n }\n for(int s=mask;s;s=(s-1)&mask){\n if(mask != (s | num[i])) continue;\n for(int len=1;len<=k;len++){\n dpSuff[i][mask][len] = (dpSuff[i][mask][len] | dpSuff[i+1][s][len - 1]);\n }\n }\n }\n }\n \n for(int ans=(1<<7)-1;ans>=0;ans--){\n for(int i=(1<<7);i>=0;i--){\n int first = i, second = (ans ^ i);\n for(int idx=0;idx<n-1;idx++){\n if(dpPref[idx][first][k] and dpSuff[idx+1][second][k]){\n return ans;\n }\n }\n }\n }\n return 0;\n }\n};\n```
0
0
['Bitmask', 'C++']
0
find-the-maximum-sequence-value-of-array
🔥BEATS 💯 % 🎯 | SUPER EASY AND SIMPLE🔥|
beats-super-easy-and-simple-by-codewiths-ba50
\n\n### Intuition\nTo solve the problem of finding the maximum XOR of two disjoint subsets of size k from an integer array, we need to break down the problem in
CodeWithSparsh
NORMAL
2024-09-15T07:38:57.513418+00:00
2024-09-15T07:38:57.513447+00:00
119
false
\n\n### Intuition\nTo solve the problem of finding the maximum XOR of two disjoint subsets of size `k` from an integer array, we need to break down the problem into manageable steps. We can use dynamic programming to compute the possible OR values for subsets of size `k` up to a certain index and from a certain index to the end. The goal is to maximize the XOR between any two such subsets.\n\n### Approach\n1. **Initialization**: \n - Create two lists, `leftMaxOrList` and `rightMaxOrList`, each of size `n`, where `n` is the length of the input array. These lists will store sets of possible OR values for subsets of size `k` up to and from each index, respectively.\n - Create `leftPossible` and `rightPossible` lists to keep track of possible OR values for subsets of size `0` to `k`.\n\n2. **Populate Left Possible ORs**:\n - Iterate through the array from left to right.\n - For each element, update possible OR values for subsets of size `1` to `k` using previously computed values.\n - Store the possible OR values for subsets of size `k` up to the current index in `leftMaxOrList`.\n\n3. **Populate Right Possible ORs**:\n - Iterate through the array from right to left.\n - For each element, update possible OR values for subsets of size `1` to `k` using previously computed values.\n - Store the possible OR values for subsets of size `k` from the current index to the end in `rightMaxOrList`.\n\n4. **Compute Maximum XOR**:\n - Iterate through all possible split points.\n - For each split point, calculate the maximum XOR value between subsets from the left and right sides.\n - Use the smaller set to minimize the number of operations in calculating the XOR.\n\n### Complexity\n- **Time Complexity**: \\(O(n \\cdot k^2)\\)\n - Building the possible OR values lists takes \\(O(n \\cdot k^2)\\) time. Each element update involves iterating through the previous possible OR values, which can be up to \\(k\\).\n - Finding the maximum XOR involves iterating through subsets from the left and right side, which is efficient given the constraints.\n\n- **Space Complexity**: \\(O(n \\cdot k)\\)\n - Space is required for storing possible OR values in `leftPossible`, `rightPossible`, `leftMaxOrList`, and `rightMaxOrList`, each of which can grow up to \\(O(n \\cdot k)\\) in size.\n\nThis approach efficiently manages the subsets and their OR values, making it feasible to compute the required maximum XOR value within acceptable time limits for typical problem constraints.\n```dart []\nimport \'dart:collection\';\n\nclass Solution {\n int maxValue(List<int> nums, int k) {\n int n = nums.length;\n if (2 * k > n) return 0;\n\n List<Set<int>> leftPossible = List.generate(k + 1, (_) => <int>{});\n leftPossible[0].add(0);\n List<Set<int>> leftMaxOrList = List.generate(n, (_) => <int>{});\n\n for (int i = 0; i < n; i++) {\n int num = nums[i];\n for (int j = k; j > 0; j--) {\n for (int orVal in leftPossible[j - 1]) {\n leftPossible[j].add(orVal | num);\n }\n }\n if (k <= i + 1) {\n leftMaxOrList[i] = Set.from(leftPossible[k]);\n }\n }\n\n List<Set<int>> rightPossible = List.generate(k + 1, (_) => <int>{});\n rightPossible[0].add(0);\n List<Set<int>> rightMaxOrList = List.generate(n, (_) => <int>{});\n\n for (int i = n - 1; i >= 0; i--) {\n int num = nums[i];\n for (int j = k; j > 0; j--) {\n for (int orVal in rightPossible[j - 1]) {\n rightPossible[j].add(orVal | num);\n }\n }\n if (k <= n - i) {\n rightMaxOrList[i] = Set.from(rightPossible[k]);\n }\n }\n\n int maxVal = 0;\n for (int i = 0; i < n - 1; i++) {\n if (i < k - 1 || (n - (i + 1)) < k) continue;\n Set<int> leftSet = leftMaxOrList[i];\n Set<int> rightSet = rightMaxOrList[i + 1];\n if (leftSet.isEmpty || rightSet.isEmpty) continue;\n\n if (leftSet.length < rightSet.length) {\n for (int or1 in leftSet) {\n for (int or2 in rightSet) {\n maxVal = max(maxVal, or1 ^ or2);\n }\n }\n } else {\n for (int or2 in rightSet) {\n for (int or1 in leftSet) {\n maxVal = max(maxVal, or1 ^ or2);\n }\n }\n }\n }\n\n return maxVal;\n }\n}\n```\n\n```java []\nimport java.util.*;\n\npublic class Solution {\n public int maxValue(int[] nums, int k) {\n int n = nums.length;\n if (2 * k > n) return 0;\n\n Set<Integer>[] leftPossible = new HashSet[k + 1];\n for (int i = 0; i <= k; i++) leftPossible[i] = new HashSet<>();\n leftPossible[0].add(0);\n Set<Integer>[] leftMaxOrList = new HashSet[n];\n for (int i = 0; i < n; i++) leftMaxOrList[i] = new HashSet<>();\n\n for (int i = 0; i < n; i++) {\n int num = nums[i];\n for (int j = k; j > 0; j--) {\n for (int orVal : leftPossible[j - 1]) {\n leftPossible[j].add(orVal | num);\n }\n }\n if (k <= i + 1) {\n leftMaxOrList[i] = new HashSet<>(leftPossible[k]);\n }\n }\n\n Set<Integer>[] rightPossible = new HashSet[k + 1];\n for (int i = 0; i <= k; i++) rightPossible[i] = new HashSet<>();\n rightPossible[0].add(0);\n Set<Integer>[] rightMaxOrList = new HashSet[n];\n for (int i = 0; i < n; i++) rightMaxOrList[i] = new HashSet<>();\n\n for (int i = n - 1; i >= 0; i--) {\n int num = nums[i];\n for (int j = k; j > 0; j--) {\n for (int orVal : rightPossible[j - 1]) {\n rightPossible[j].add(orVal | num);\n }\n }\n if (k <= n - i) {\n rightMaxOrList[i] = new HashSet<>(rightPossible[k]);\n }\n }\n\n int maxVal = 0;\n for (int i = 0; i < n - 1; i++) {\n if (i < k - 1 || (n - (i + 1)) < k) continue;\n Set<Integer> leftSet = leftMaxOrList[i];\n Set<Integer> rightSet = rightMaxOrList[i + 1];\n if (leftSet.isEmpty() || rightSet.isEmpty()) continue;\n\n if (leftSet.size() < rightSet.size()) {\n for (int or1 : leftSet) {\n for (int or2 : rightSet) {\n maxVal = Math.max(maxVal, or1 ^ or2);\n }\n }\n } else {\n for (int or2 : rightSet) {\n for (int or1 : leftSet) {\n maxVal = Math.max(maxVal, or1 ^ or2);\n }\n }\n }\n }\n\n return maxVal;\n }\n}\n```\n\n```javascript []\nfunction maxValue(nums, k) {\n const n = nums.length;\n if (2 * k > n) return 0;\n\n const leftPossible = Array.from({ length: k + 1 }, () => new Set());\n leftPossible[0].add(0);\n const leftMaxOrList = Array.from({ length: n }, () => new Set());\n\n for (let i = 0; i < n; i++) {\n const num = nums[i];\n for (let j = k; j > 0; j--) {\n for (const orVal of leftPossible[j - 1]) {\n leftPossible[j].add(orVal | num);\n }\n }\n if (k <= i + 1) {\n leftMaxOrList[i] = new Set(leftPossible[k]);\n }\n }\n\n const rightPossible = Array.from({ length: k + 1 }, () => new Set());\n rightPossible[0].add(0);\n const rightMaxOrList = Array.from({ length: n }, () => new Set());\n\n for (let i = n - 1; i >= 0; i--) {\n const num = nums[i];\n for (let j = k; j > 0; j--) {\n for (const orVal of rightPossible[j - 1]) {\n rightPossible[j].add(orVal | num);\n }\n }\n if (k <= n - i) {\n rightMaxOrList[i] = new Set(rightPossible[k]);\n }\n }\n\n let maxVal = 0;\n for (let i = 0; i < n - 1; i++) {\n if (i < k - 1 || (n - (i + 1)) < k) continue;\n const leftSet = leftMaxOrList[i];\n const rightSet = rightMaxOrList[i + 1];\n if (leftSet.size === 0 || rightSet.size === 0) continue;\n\n if (leftSet.size < rightSet.size) {\n for (const or1 of leftSet) {\n for (const or2 of rightSet) {\n maxVal = Math.max(maxVal, or1 ^ or2);\n }\n }\n } else {\n for (const or2 of rightSet) {\n for (const or1 of leftSet) {\n maxVal = Math.max(maxVal, or1 ^ or2);\n }\n }\n }\n }\n\n return maxVal;\n}\n```\n\n```cpp []\n#include <vector>\n#include <unordered_set>\n#include <algorithm>\nusing namespace std;\n\nclass Solution {\npublic:\n int maxValue(vector<int>& nums, int k) {\n int n = nums.size();\n if (2 * k > n) return 0;\n\n vector<unordered_set<int>> leftPossible(k + 1);\n leftPossible[0].insert(0);\n vector<unordered_set<int>> leftMaxOrList(n);\n\n for (int i = 0; i < n; i++) {\n int num = nums[i];\n for (int j = k; j > 0; j--) {\n for (int orVal : leftPossible[j - 1]) {\n leftPossible[j].insert(orVal | num);\n }\n }\n if (k <= i + 1) {\n leftMaxOrList[i] = leftPossible[k];\n }\n }\n\n vector<unordered_set<int>> rightPossible(k + 1);\n rightPossible[0].insert(0);\n vector<unordered_set<int>> rightMaxOrList(n);\n\n for (int i = n - 1; i >= 0; i--) {\n int num = nums[i];\n for (int j = k; j > 0; j--) {\n for (int orVal : rightPossible[j - 1]) {\n rightPossible[j].insert(orVal | num);\n }\n }\n if (\n\nk <= n - i) {\n rightMaxOrList[i] = rightPossible[k];\n }\n }\n\n int maxVal = 0;\n for (int i = 0; i < n - 1; i++) {\n if (i < k - 1 || (n - (i + 1)) < k) continue;\n const unordered_set<int>& leftSet = leftMaxOrList[i];\n const unordered_set<int>& rightSet = rightMaxOrList[i + 1];\n if (leftSet.empty() || rightSet.empty()) continue;\n\n if (leftSet.size() < rightSet.size()) {\n for (int or1 : leftSet) {\n for (int or2 : rightSet) {\n maxVal = max(maxVal, or1 ^ or2);\n }\n }\n } else {\n for (int or2 : rightSet) {\n for (int or1 : leftSet) {\n maxVal = max(maxVal, or1 ^ or2);\n }\n }\n }\n }\n\n return maxVal;\n }\n};\n```\n\n```c []\n#include <stdio.h>\n#include <stdlib.h>\n\n#define MAX_SIZE 10000\n\ntypedef struct {\n int size;\n int data[MAX_SIZE];\n} Set;\n\nvoid initSet(Set *set) {\n set->size = 0;\n}\n\nint contains(Set *set, int value) {\n for (int i = 0; i < set->size; i++) {\n if (set->data[i] == value) return 1;\n }\n return 0;\n}\n\nvoid add(Set *set, int value) {\n if (!contains(set, value)) {\n set->data[set->size++] = value;\n }\n}\n\nint maxValue(int* nums, int numsSize, int k) {\n if (2 * k > numsSize) return 0;\n\n Set leftPossible[k + 1];\n for (int i = 0; i <= k; i++) initSet(&leftPossible[i]);\n add(&leftPossible[0], 0);\n\n Set leftMaxOrList[numsSize];\n for (int i = 0; i < numsSize; i++) initSet(&leftMaxOrList[i]);\n\n for (int i = 0; i < numsSize; i++) {\n int num = nums[i];\n for (int j = k; j > 0; j--) {\n for (int l = 0; l < leftPossible[j - 1].size; l++) {\n add(&leftPossible[j], leftPossible[j - 1].data[l] | num);\n }\n }\n if (k <= i + 1) {\n for (int l = 0; l < leftPossible[k].size; l++) {\n add(&leftMaxOrList[i], leftPossible[k].data[l]);\n }\n }\n }\n\n Set rightPossible[k + 1];\n for (int i = 0; i <= k; i++) initSet(&rightPossible[i]);\n add(&rightPossible[0], 0);\n\n Set rightMaxOrList[numsSize];\n for (int i = 0; i < numsSize; i++) initSet(&rightMaxOrList[i]);\n\n for (int i = numsSize - 1; i >= 0; i--) {\n int num = nums[i];\n for (int j = k; j > 0; j--) {\n for (int l = 0; l < rightPossible[j - 1].size; l++) {\n add(&rightPossible[j], rightPossible[j - 1].data[l] | num);\n }\n }\n if (k <= numsSize - i) {\n for (int l = 0; l < rightPossible[k].size; l++) {\n add(&rightMaxOrList[i], rightPossible[k].data[l]);\n }\n }\n }\n\n int maxVal = 0;\n for (int i = 0; i < numsSize - 1; i++) {\n if (i < k - 1 || (numsSize - (i + 1)) < k) continue;\n Set* leftSet = &leftMaxOrList[i];\n Set* rightSet = &rightMaxOrList[i + 1];\n if (leftSet->size == 0 || rightSet->size == 0) continue;\n\n if (leftSet->size < rightSet->size) {\n for (int l = 0; l < leftSet->size; l++) {\n for (int m = 0; m < rightSet->size; m++) {\n int or1 = leftSet->data[l];\n int or2 = rightSet->data[m];\n maxVal = max(maxVal, or1 ^ or2);\n }\n }\n } else {\n for (int m = 0; m < rightSet->size; m++) {\n for (int l = 0; l < leftSet->size; l++) {\n int or1 = leftSet->data[l];\n int or2 = rightSet->data[m];\n maxVal = max(maxVal, or1 ^ or2);\n }\n }\n }\n }\n\n return maxVal;\n}\n```\n\n```python []\nfrom typing import List\n\nclass Solution:\n def maxValue(self, nums: List[int], k: int) -> int:\n n = len(nums)\n if 2 * k > n:\n return 0\n\n left_possible = [set() for _ in range(k + 1)]\n left_possible[0].add(0)\n left_max_or_list = [set() for _ in range(n)]\n\n for i in range(n):\n num = nums[i]\n for j in range(k, 0, -1):\n for or_val in left_possible[j - 1]:\n left_possible[j].add(or_val | num)\n if k <= i + 1:\n left_max_or_list[i] = set(left_possible[k])\n\n right_possible = [set() for _ in range(k + 1)]\n right_possible[0].add(0)\n right_max_or_list = [set() for _ in range(n)]\n\n for i in range(n - 1, -1, -1):\n num = nums[i]\n for j in range(k, 0, -1):\n for or_val in right_possible[j - 1]:\n right_possible[j].add(or_val | num)\n if k <= n - i:\n right_max_or_list[i] = set(right_possible[k])\n\n max_val = 0\n for i in range(n - 1):\n if i < k - 1 or (n - (i + 1)) < k:\n continue\n left_set = left_max_or_list[i]\n right_set = right_max_or_list[i + 1]\n if not left_set or not right_set:\n continue\n\n if len(left_set) < len(right_set):\n for or1 in left_set:\n for or2 in right_set:\n max_val = max(max_val, or1 ^ or2)\n else:\n for or2 in right_set:\n for or1 in left_set:\n max_val = max(max_val, or1 ^ or2)\n\n return max_val\n```\n\n```go []\npackage main\n\nimport "math"\n\nfunc maxValue(nums []int, k int) int {\n n := len(nums)\n if 2*k > n {\n return 0\n }\n\n leftPossible := make([]map[int]struct{}, k+1)\n for i := range leftPossible {\n leftPossible[i] = make(map[int]struct{})\n }\n leftPossible[0][0] = struct{}{}\n leftMaxOrList := make([]map[int]struct{}, n)\n for i := range leftMaxOrList {\n leftMaxOrList[i] = make(map[int]struct{})\n }\n\n for i := 0; i < n; i++ {\n num := nums[i]\n for j := k; j > 0; j-- {\n for orVal := range leftPossible[j-1] {\n leftPossible[j][orVal|num] = struct{}{}\n }\n }\n if k <= i+1 {\n for orVal := range leftPossible[k] {\n leftMaxOrList[i][orVal] = struct{}{}\n }\n }\n }\n\n rightPossible := make([]map[int]struct{}, k+1)\n for i := range rightPossible {\n rightPossible[i] = make(map[int]struct{})\n }\n rightPossible[0][0] = struct{}{}\n rightMaxOrList := make([]map[int]struct{}, n)\n for i := range rightMaxOrList {\n rightMaxOrList[i] = make(map[int]struct{})\n }\n\n for i := n - 1; i >= 0; i-- {\n num := nums[i]\n for j := k; j > 0; j-- {\n for orVal := range rightPossible[j-1] {\n rightPossible[j][orVal|num] = struct{}{}\n }\n }\n if k <= n-i {\n for orVal := range rightPossible[k] {\n rightMaxOrList[i][orVal] = struct{}{}\n }\n }\n }\n\n maxVal := 0\n for i := 0; i < n-1; i++ {\n if i < k-1 || (n-(i+1)) < k {\n \n\n continue\n }\n leftSet := leftMaxOrList[i]\n rightSet := rightMaxOrList[i+1]\n if len(leftSet) == 0 || len(rightSet) == 0 {\n continue\n }\n\n if len(leftSet) < len(rightSet) {\n for or1 := range leftSet {\n for or2 := range rightSet {\n maxVal = int(math.Max(float64(maxVal), float64(or1^or2)))\n }\n }\n } else {\n for or2 := range rightSet {\n for or1 := range leftSet {\n maxVal = int(math.Max(float64(maxVal), float64(or1^or2)))\n }\n }\n }\n }\n\n return maxVal\n}\n```\n\n```typescript []\nclass Solution {\n maxValue(nums: number[], k: number): number {\n const n = nums.length;\n if (2 * k > n) return 0;\n\n const leftPossible: Set<number>[] = Array.from({ length: k + 1 }, () => new Set<number>());\n leftPossible[0].add(0);\n const leftMaxOrList: Set<number>[] = Array.from({ length: n }, () => new Set<number>());\n\n for (let i = 0; i < n; i++) {\n const num = nums[i];\n for (let j = k; j > 0; j--) {\n for (const orVal of leftPossible[j - 1]) {\n leftPossible[j].add(orVal | num);\n }\n }\n if (k <= i + 1) {\n for (const orVal of leftPossible[k]) {\n leftMaxOrList[i].add(orVal);\n }\n }\n }\n\n const rightPossible: Set<number>[] = Array.from({ length: k + 1 }, () => new Set<number>());\n rightPossible[0].add(0);\n const rightMaxOrList: Set<number>[] = Array.from({ length: n }, () => new Set<number>());\n\n for (let i = n - 1; i >= 0; i--) {\n const num = nums[i];\n for (let j = k; j > 0; j--) {\n for (const orVal of rightPossible[j - 1]) {\n rightPossible[j].add(orVal | num);\n }\n }\n if (k <= n - i) {\n for (const orVal of rightPossible[k]) {\n rightMaxOrList[i].add(orVal);\n }\n }\n }\n\n let maxVal = 0;\n for (let i = 0; i < n - 1; i++) {\n if (i < k - 1 || (n - (i + 1)) < k) continue;\n const leftSet = leftMaxOrList[i];\n const rightSet = rightMaxOrList[i + 1];\n if (leftSet.size === 0 || rightSet.size === 0) continue;\n\n if (leftSet.size < rightSet.size) {\n for (const or1 of leftSet) {\n for (const or2 of rightSet) {\n maxVal = Math.max(maxVal, or1 ^ or2);\n }\n }\n } else {\n for (const or2 of rightSet) {\n for (const or1 of leftSet) {\n maxVal = Math.max(maxVal, or1 ^ or2);\n }\n }\n }\n }\n\n return maxVal;\n }\n}\n```
0
0
['C', 'C++', 'Java', 'Go', 'TypeScript', 'Python3', 'JavaScript', 'Dart']
0
find-the-maximum-sequence-value-of-array
✅The Godfather👑 of Python3 🔥Beats 100%
the-godfather-of-python3-beats-100-by-sr-2cwk
Intuition: Believe in Yourself\n Describe your first thoughts on how to solve this problem. \n\n# Approach: Just Do It\n Describe your approach to solving the p
srijandawn
NORMAL
2024-09-14T16:38:56.523684+00:00
2024-09-14T16:38:56.523719+00:00
89
false
# Intuition: Believe in Yourself\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach: Just Do It\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity: None\n- Time Complexity : **_LOKI_**\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space Complexity : **_THOR_**\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```python3 []\nclass Solution:\n def maxValue(self, nums: List[int], k: int) -> int:\n n = len(nums)\n \n def get_possible(a):\n t1 = {(0, 0)}\n d = defaultdict(lambda: -1)\n for i, x in enumerate(a):\n t2 = set()\n for taken, val in t1:\n if taken < k:\n t2.add((taken + 1, val | x))\n if taken + 1 == k and val | x not in d:\n d[val | x] = i + 1\n t1.update(t2)\n return d\n \n a = get_possible(nums)\n b = get_possible(nums[::-1])\n ans = -float(\'inf\')\n \n for v1, x in a.items():\n for v2, y in b.items():\n if x + y <= n:\n ans = max(ans, v1 ^ v2)\n \n return ans\n```
0
1
['Python3']
0
find-the-maximum-sequence-value-of-array
Java || Simple 5 Step Process🔥🔥|| Beats 100% ☑☑||Line by Line Code Explaination🥳
java-simple-5-step-process-beats-100-lin-ubap
\n\n# Approach\n1. Two-part problem : The problem asks to find the maximum value of a subsequence of size 2 * k in an array nums, where the value is defined as:
SKSingh0703
NORMAL
2024-09-14T16:33:04.654511+00:00
2024-09-14T16:33:04.654534+00:00
153
false
![image.png](https://assets.leetcode.com/users/images/20e95967-7d9f-4bab-8644-e708615ba31d_1726330748.386492.png)\n\n# Approach\n1. **Two-part problem :** The problem asks to find the maximum value of a subsequence of size 2 * k in an array nums, where the value is defined as:\n\n **(OR\xA0of\xA0the\xA0first\xA0half\xA0of\xA0subsequence) XOR (OR\xA0of\xA0the\xA0second\xA0half\xA0of\xA0subsequence)**.\n\n**We need to split the subsequence of size 2 * k into two halves and calculate the OR for both halves, then compute the XOR of these two values**.\n\n2. **DP and Set-based approach**:\n\n- **Sets : For each index i, we maintain two 2D arrays, left and right, where each entry is a set that stores all possible OR results of subarrays of length j ending at or before i (for left) or starting at or after i (for right)**.\n- The goal is to explore all possible subsequences of length 2 * k, split them into two parts (left half and right half), compute the OR for both halves, and maximize the XOR of these two OR values.\n3. **Left-to-right DP:**\n\n- For each element in nums from the start, calculate the possible OR results for subarrays of length 1 to k using dynamic programming, and store these results in the left array.\nleft[i][j] represents all possible OR results for subarrays ending at index i of size j.\n- **The idea is** that, as you iterate through the nums array, you calculate the OR results for all subarrays ending at each element. You keep track of all OR results for each subarray size, because the XOR computation requires considering the OR results from the first half of the subsequence and the second half. Thus, by precomputing the OR results, you can efficiently maximize the XOR value later.\n4. Right-to-left DP:\n\n- Similarly, process the array in reverse to calculate the possible OR results for subarrays starting from each element, and store these results in the right array.\nright[i][j] stores OR results for subarrays starting at index i of size j.\n5. Maximizing the XOR:\n\n- Once the left and right sets are populated, for each index i, we compute the XOR between the OR results of the left half (left[i-1][k]) and the right half (right[i][k]).\nKeep track of the maximum XOR value.\n\n# Complexity\n- Time complexity: O(N*K)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(N*K)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```java []\nclass Solution {\n public int maxValue(int[] nums, int k) {\n int n = nums.length;\n Set<Integer>[][] left = new Set[n][k + 1];\n Set<Integer>[][] right = new Set[n][k + 1];\n\n for (int i = 0; i < n; i++) {\n \tfor (int j = 0; j <= k; j++) {\n\t \tleft[i][j] = new HashSet();\n\t \tright[i][j] = new HashSet();\n \t}\n }\n\n left[0][0].add(0);\n left[0][1].add(nums[0]);\n\n for (int i = 1; i < n - k; i++) {\n \tleft[i][0].add(0);\n \tfor (int j = 1; j <= k; j++) {\n \t\tleft[i][j].addAll(left[i - 1][j]);\n \t\tfor (int v : left[i - 1][j - 1])\n \t\t\tleft[i][j].add(v | nums[i]);\n \t}\n }\n\n right[n - 1][0].add(0);\n right[n - 1][1].add(nums[n - 1]);\n\n int result = 0;\n\n if (k == 1) {\n for (int l : left[n - 2][k])\n result = Math.max(result, l ^ nums[n - 1]); \n }\n\n for (int i = n - 2; i >= k; i--) {\n \tright[i][0].add(0);\n \tfor (int j = 1; j <= k; j++) {\n \t\tright[i][j].addAll(right[i + 1][j]);\n \t\tfor (int v : right[i + 1][j - 1])\n \t\t\tright[i][j].add(v | nums[i]);\n \t}\n \tfor (int l : left[i - 1][k]) {\n \t\tfor (int r : right[i][k])\n \t\t\tresult = Math.max(result, l ^ r);\n \t}\n }\n \n return result;\n }\n}\n\n```
0
0
['Dynamic Programming', 'Java']
0
find-the-maximum-sequence-value-of-array
Beats 100%
beats-100-by-hitanshparikh-mkj5
Code\npython3 []\nclass Solution:\n def maxValue(self, nums: List[int], k: int) -> int:\n n = len(nums)\n \n def get_possible(a):\n
HitanshParikh
NORMAL
2024-09-14T16:23:40.416705+00:00
2024-09-14T16:23:40.416729+00:00
113
false
# Code\n```python3 []\nclass Solution:\n def maxValue(self, nums: List[int], k: int) -> int:\n n = len(nums)\n \n def get_possible(a):\n t1 = {(0, 0)}\n d = defaultdict(lambda: -1)\n for i, x in enumerate(a):\n t2 = set()\n for taken, val in t1:\n if taken < k:\n t2.add((taken + 1, val | x))\n if taken + 1 == k and val | x not in d:\n d[val | x] = i + 1\n t1.update(t2)\n return d\n \n a = get_possible(nums)\n b = get_possible(nums[::-1])\n ans = -float(\'inf\')\n \n for v1, x in a.items():\n for v2, y in b.items():\n if x + y <= n:\n ans = max(ans, v1 ^ v2)\n \n return ans\n```
0
0
['Python3']
1
find-the-maximum-sequence-value-of-array
easy python solution
easy-python-solution-by-enkixly-ssfx
Code\npython3 []\nfrom typing import List\nfrom collections import defaultdict\nfrom math import inf\n\nclass Solution:\n def maxValue(self, array: List[int]
enkixly
NORMAL
2024-09-14T16:03:57.226952+00:00
2024-09-14T16:03:57.226985+00:00
287
false
# Code\n```python3 []\nfrom typing import List\nfrom collections import defaultdict\nfrom math import inf\n\nclass Solution:\n def maxValue(self, array: List[int], maxCount: int) -> int:\n length = len(array)\n\n def calculatePossibleConfigs(elements):\n initial_set = set([(0, 0)])\n state_dict = defaultdict(lambda: -1)\n for index, number in enumerate(elements):\n new_set = set()\n for count, bitmask in initial_set:\n if count < maxCount:\n new_set.add((count + 1, bitmask | number))\n if count + 1 == maxCount:\n if bitmask | number not in state_dict:\n state_dict[bitmask | number] = index + 1\n initial_set |= new_set\n return state_dict\n\n forward_config = calculatePossibleConfigs(array)\n reverse_config = calculatePossibleConfigs(array[::-1])\n result = -inf\n\n for bitmask1, position1 in forward_config.items():\n for bitmask2, position2 in reverse_config.items():\n if position1 + position2 <= length:\n result = max(result, bitmask1 ^ bitmask2)\n \n return result\n\n```
0
0
['Python3']
2
find-the-maximum-sequence-value-of-array
Minimum ending pos for all subsequenceOR O(n*n)
minimum-ending-pos-for-all-subsequenceor-bf8g
Intuition\nThere can be maximum min(2^7,n8) unique subsequence OR.\n(This problem is possible even for nums[i]<1e9)\n\n# Approach\nCreate a map of bitwise or of
sandeep_p
NORMAL
2024-09-14T16:02:43.564393+00:00
2024-09-14T17:18:01.587165+00:00
204
false
# Intuition\nThere can be maximum min(2^7,n*8) unique subsequence OR.\n(This problem is possible even for nums[i]<1e9)\n\n# Approach\nCreate a map of bitwise or of all subsequences of length k , keeping track of minimum ending index.\n`d[SUBSEQUNCE_OR]=min_end_index+1`\nDo the same for reversed array.\n\nFor each combination of SUBSEQUNCE_ORs for forwards and backwards array. if sum of min_end_index+1 is <=n There is no overlap in subsequences. take the max xor for combination.\n\n\n# Complexity\n- Time complexity:\nO(n*n)\n\n- Space complexity:\nO(n*n)\n\n# Code\n```python3 []\nclass Solution:\n def maxValue(self, nums: List[int], k: int) -> int:\n n=len(nums)\n def get_map(a): # d[SUBSEEUQNCE_OR]=min_end_index+1\n dp0=set([(0,0)])\n d=defaultdict(lambda :-1)\n for i,x in enumerate(a):\n dp1=set()\n for taken,val in dp0:\n if taken<k:\n dp1.add( (taken+1,val|x) )\n if taken+1==k:\n if val|x not in d:\n d[val|x]=i+1\n dp0|=dp1\n return d\n a=get_map(nums)\n b=get_map(nums[::-1])\n ans=-inf\n for v1,x in a.items():\n for v2,y in b.items():\n if x+y<=n:\n ans=max(ans,v1^v2)\n return ans\n```
0
0
['Python3']
0
find-the-maximum-sequence-value-of-array
[Python] OR accumulate left and right halves with explanation
python-3-with-explanation-by-phamphihung-131p
IntuitionThis solution just rewrite solution from @lee215. Actually it's quite hard to understand this problem and it took me a while to get the idea behind it.
phamphihungbk
NORMAL
2024-12-11T21:54:13.877370+00:00
2024-12-26T12:15:57.514501+00:00
24
false
# Intuition This solution just rewrite solution from @lee215. Actually it's quite hard to understand this problem and it took me a while to get the idea behind it. So I will explan what I understood and hope it's more clear for you. **Recap:** you are given nums array and postive integer k return maximum xor value of OR all values from left sequence and OR all values from right sequence such that size of left sequence and right sequence is `2*k` Let's say we have this example nums = [2, 6, 7], k = 1 we have 3 subsequence with size is 2 - [2, 6] -> 2^6 = 4 - [2, 7] -> 2^7 = 5 - [6, 7] -> 6^7 = 1 and the answer is 2^7 = 5 from example above we may think we somehow need to find all individual sub sequence, do xor left and right halve for each sub sequence and compare between of them. but this will bit complicated. are there other way like we do the OR of left halve all sub sequence, also same for right halve and compare the xor for all of them. So answer is we can because looks at example it can be (2|2|6) ^ (6|7|7) or (2|6)^(6|7) or 2^7|6^6 because 6^6 = 0 so we have 2^7 = 5 from this we have some observations: - left halve and right halve of sub sequence should not have overlap - the or values we don't need duplicated values - we can do accumulate OR of all values of left halve, accordingly to right halve # Approach - at each index of nums we try to split left halve and right halve and compute OR with this way we can avoid overlapping - to prevent duplicated OR value, we will use set() instead of list - since we can do accumulate OR for left halve of all possible sub sequence we found so combine all values at the end with `skip_current | include_current` # Complexity - Time complexity: O(2^2k * n) to find subset we have two choice (choose or not) with k element so compute_or_values in worst case takes 2^k two for loop (left_or_values and right_or_values) takes 2^k * 2^k = 2^2k or 4^k so final 2^2k * n (is outer for loop) - Space complexity: 2^k*n due to unique state of compute_or_values # Code ```python3 [] class Solution: def maxValue(self, nums: List[int], k: int) -> int: @lru_cache(None) def compute_or_values(index: int, remaining: int, direction: int) -> set if remaining == 0: # why because 0 | x = x return {0} if index < 0 or index >= len(nums): return set() # empty # Option 1: Include the current element and compute the OR include_current = {nums[index] | v for v in compute_or_values(index + direction, remaining - 1, direction)} # product {} if compute_or_values(index + direction, remaining - 1, direction) return {} # Option 2: Skip the current element skip_current = compute_or_values(index + direction, remaining, direction) # Return the union of both options return skip_current | include_current max_result = 0 for i in range(len(nums)): left_or_values = compute_or_values(i, k, -1) # Compute OR values for k elements to the left of i right_or_values = compute_or_values(i + 1, k, 1) # Compute OR values for k elements to the right of i + 1 for left_val in left_or_values: for right_val in right_or_values: max_result = max(max_result, left_val ^ right_val) return max_result ```
0
0
['Dynamic Programming', 'Recursion', 'Python3']
0
k-inverse-pairs-array
Java DP O(nk) solution
java-dp-onk-solution-by-dreamchase-cpbr
dp[n][k] denotes the number of arrays that have k inverse pairs for array composed of 1 to n\nwe can establish the recursive relationship between dp[n][k] and d
dreamchase
NORMAL
2017-06-25T18:34:05.566000+00:00
2018-10-23T20:28:57.917411+00:00
23,356
false
dp[n][k] denotes the number of arrays that have k inverse pairs for array composed of 1 to n\nwe can establish the recursive relationship between dp[n][k] and dp[n-1][i]:\n\n\nif we put n as the last number then all the k inverse pair should come from the first n-1 numbers\nif we put n as the second last number then there's 1 inverse pair involves n so the rest k-1 comes from the first n-1 numbers\n...\nif we put n as the first number then there's n-1 inverse pairs involve n so the rest k-(n-1) comes from the first n-1 numbers\n\n<code>dp[n][k] = dp[n-1][k]+dp[n-1][k-1]+dp[n-1][k-2]+...+dp[n-1][k+1-n+1]+dp[n-1][k-n+1]</code>\n\nIt's possible that some where in the right hand side the second array index become negative, since we cannot generate negative inverse pairs we just treat them as 0, but still leave the item there as a place holder.\n\n<code>dp[n][k] = dp[n-1][k]+dp[n-1][k-1]+dp[n-1][k-2]+...+dp[n-1][k+1-n+1]+dp[n-1][k-n+1]</code>\n<code>dp[n][k+1] = dp[n-1][k+1]+dp[n-1][k]+dp[n-1][k-1]+dp[n-1][k-2]+...+dp[n-1][k+1-n+1] </code>\n\nso by deducting the first line from the second line, we have\n\n<code>dp[n][k+1] = dp[n][k]+dp[n-1][k+1]-dp[n-1][k+1-n]</code>\n\nBelow is the java code:\n```\n public static int kInversePairs(int n, int k) {\n int mod = 1000000007;\n if (k > n*(n-1)/2 || k < 0) return 0;\n if (k == 0 || k == n*(n-1)/2) return 1;\n long[][] dp = new long[n+1][k+1];\n dp[2][0] = 1;\n dp[2][1] = 1;\n for (int i = 3; i <= n; i++) {\n dp[i][0] = 1;\n for (int j = 1; j <= Math.min(k, i*(i-1)/2); j++) {\n dp[i][j] = dp[i][j-1] + dp[i-1][j];\n if (j >= i) dp[i][j] -= dp[i-1][j-i];\n dp[i][j] = (dp[i][j]+mod) % mod;\n }\n }\n return (int) dp[n][k];\n }
270
3
[]
31
k-inverse-pairs-array
C++ 4 solutions with picture
c-4-solutions-with-picture-by-votrubac-50ah
Intuition\nIf we have numbers [1..n], and we put 1 in the first position, it will create no inversions with the rest of the array. If we choose 2 for the first
votrubac
NORMAL
2020-09-14T08:25:41.927685+00:00
2020-09-15T08:01:13.547079+00:00
18,804
false
#### Intuition\nIf we have numbers `[1..n]`, and we put `1` in the first position, it will create no inversions with the rest of the array. If we choose `2` for the first position, it will create one inversion. If we choose `n` for the first position, it will create `n - 1` inversion with the rest of the array.\n\nWe can see a recursion here - we can now apply the same logic for `n - 1` and `k - i + 1`, where `i` is the number we choose for the first position in the previous step.\n\nSimilar question: [903. Valid Permutations for DI Sequence](https://leetcode.com/problems/valid-permutations-for-di-sequence/).\n\n#### Top-Down DP\nWe will start with the most intuitive implementation, which, with the help of memoisation, will have O(n * k * k) time complexity. \n\n> Note that this and the following solutions are not accepted by OJ. They are here for demonstration purposes. We will build it up to O(n * k) solution in the end.\n```cpp\nint dp[1001][1001] = {};\nint kInversePairs(int n, int k) {\n if (k <= 0)\n return k == 0;\n if (dp[n][k] == 0) {\n dp[n][k] = 1;\n for (auto i = 0; i < n; ++i) {\n dp[n][k] = (dp[n][k] + kInversePairs(n - 1, k - i)) % 1000000007;\n }\n }\n return dp[n][k] - 1;\n}\n```\n**Complexity Analysis**\n- Time: O(n * k * k)\n- Memory: O(n * k)\n\n#### Bottom-Up DP\nAfter we get the top-down memoisation right, we can convert it to a bottom-up tabulation. A tabulation algorithm is iterative, and it often leads to further runtime and/or memory optimizations.\n```cpp\nint kInversePairs(int n, int k) {\n int dp[1001][1001] = { 1 };\n for (int N = 1; N <= n; ++N)\n for (int K = 0; K <= k; ++K)\n for (int i = 0; i <= min(K, N - 1); ++i) \n dp[N][K] = (dp[N][K] + dp[N - 1][K - i]) % 1000000007;\n return dp[n][k];\n}\n```\n**Complexity Analysis**\n- Same as for top-down approach.\n\n#### Time Optimization\nAs it happens, the bottom-up DP gives us an insight that can improve the time complexity. If you look at the inner loop, you can realize that it iterates over the (K - 1) values for the next K. It becomes very clear if you look how the tabulation matrix is populated.\n![image](https://assets.leetcode.com/users/images/8da5904b-54b6-4640-8c54-9fb8209aa940_1600155145.977385.png)\n\nIn the picture above, you can see that value for n == 5 is a sum of 5 values in the previous column: dp[N - 1][K] + dp[N - 1][K-1]+... + dp[N-1][K - 4]. For the next value - `K + 1`, we can add to that value dp[N - 1][K + 1], and subtract dp[N - 1][K - 4].\n\nTherefore, we can use a sliding window technique to calculate `dp[N][K]` in O(1), reducing the overall time complexity to O(n * k).\n\n```cpp\nint dp[1001][1001] = { 1 };\nclass Solution {\npublic:\n int kInversePairs(int n, int k) {\n if (dp[n][k])\n return dp[n][k];\n for (int N = 1; N <= n; ++N)\n for (int K = 0; K <= k; ++K) {\n dp[N][K] = (dp[N - 1][K] + (K > 0 ? dp[N][K - 1] : 0)) % 1000000007;\n if (K >= N)\n dp[N][K] = (1000000007 + dp[N][K] - dp[N - 1][K - N]) % 1000000007;\n }\n return dp[n][k];\n }\n};\n```\n**Complexity Analysis**\n- Time: O(n * k)\n- Memory: O(n * k)\n\n#### Memory Optimization\nFrom the above algorithm, you can notice that we only look one step back (N - 1). Therefore, we only need two rows (`k` column each) for the tabulation.\n```\nint kInversePairs(int n, int k) {\n int dp[2][1001] = { 1 };\n for (int N = 1; N <= n; ++N)\n for (int K = 0; K <= k; ++K) {\n dp[N % 2][K] = (dp[(N - 1) % 2][K] + (K > 0 ? dp[N % 2][K - 1] : 0)) % 1000000007;\n if (K >= N)\n dp[N % 2][K] = (1000000007 + dp[N % 2][K] - dp[(N - 1) % 2][K - N]) % 1000000007;\n }\n return dp[n % 2][k];\n}\n```\n**Complexity Analysis**\n- Time: O(n * k)\n- Memory: O(k)
233
1
[]
18
k-inverse-pairs-array
🔥 All 4 DP Solutions 🔥 Hard made Easy
all-4-dp-solutions-hard-made-easy-by-bha-e15r
Intuition\nLet\'s say we have n elements in our permutation then Depending on where we put the element (n+1) in our permutation, we may add 0, 1, 2, ..., n new
bhavik_11
NORMAL
2024-01-27T05:45:02.155743+00:00
2024-01-27T05:45:02.155774+00:00
11,363
false
# Intuition\nLet\'s say we have n elements in our permutation then Depending on where we put the element (n+1) in our permutation, we may add 0, 1, 2, ..., n new inverse pairs. For example, if we have some permutation of 1...4, then:\n\n- 5 x x x x creates 4 new inverse pairs\n- x 5 x x x creates 3 new inverse pairs\n ...\n- x x x x 5 creates 0 new inverse pairs\n\n\n# Approach\ndp[n][k] = dp[n - 1][k - 0] + dp[n - 1][k - 1] + ... + dp[n - 1][k - (n - 1)]\n\n\n# Complexity\n- Time complexity: $$O(n*k*k)$$ to $$O(n*k)$$\n\n- Space complexity:$$O(n*k)$$ to $$O(k)$$\n\n# Code\n# Memoization\n```\nclass Solution {\nprivate:\n const int mod=int(1e9+7);\n int dp[1001][1001];\n int f(int n,int k) {\n //base case\n if(k<=0) return k==0;\n if(dp[n][k]!=-1) return dp[n][k];\n\n\n int ans=0;\n for(int i=0;i<n;++i) {\n ans+=f(n-1,k-i);\n ans%=mod;\n }\n return dp[n][k]=ans;\n }\npublic:\n int kInversePairs(int n, int k) {\n memset(dp,-1,sizeof(dp));\n return f(n,k);\n }\n};\n```\n\n# Tabulation\n```\nclass Solution {\nprivate:\n const int mod=int(1e9+7);\npublic:\n int kInversePairs(int n, int k) {\n vector<vector<int>> dp(n+1,vector<int>(k+1,0));\n //base case\n for(int N=0;N<=n;++N) dp[N][0]=1;\n for(int N=1;N<=n;++N) {\n for(int K=0;K<=k;++K) {\n int ans=0;\n for(int i=0;i<min(N,K+1);++i) {\n ans+=dp[N-1][K-i];\n ans%=mod;\n }\n dp[N][K]=ans;\n }\n }\n return dp[n][k];\n }\n};\n```\n\n# Optimization Idea\n\nf(n, k) = f(n-1, k) + f(n-1, k-1) + f(n-1, k-2) + ... + f(n-1, k-n+1) --->(1)\n\nf(n, k-1) = f(n-1, k-1) + f(n-1, k-2) + f(n-1, k-3) + ... + f(n-1, k-n+1)+ f(n-1, k-n) --->(2)\n\nsubtract eqn 2 from eqn 1,we get\n\n**f(n, k) = f(n, k-1) + f(n-1, k) - f(n-1, k-n)**\n\n\n# Time-Optimized Tabulation\n```\nclass Solution {\nprivate:\n const int mod=int(1e9+7);\npublic:\n int kInversePairs(int n, int k) {\n vector<vector<int>> dp(n+1,vector<int>(k+1,0));\n //base case\n for(int N=0;N<=n;++N) dp[N][0]=1;\n for(int N=1;N<=n;++N) {\n for(int K=0;K<=k;++K) {\n dp[N][K] = (dp[N - 1][K] + (K > 0 ? dp[N][K - 1] : 0)) % mod;\n dp[N][K] = (dp[N][K] + mod - (K >= N ? dp[N-1][K-N] : 0)) % mod;\n }\n }\n return dp[n][k];\n }\n};\n```\n\n# Time & Space Optimized Tabulation\n```\nclass Solution {\nprivate:\n const int mod=int(1e9+7);\npublic:\n int kInversePairs(int n, int k) {\n vector<int> prev(k+1,0),curr(k+1,0);\n prev[0]=curr[0]=1;\n for(int N=1;N<=n;++N) {\n for(int K=0;K<=k;++K) {\n curr[K] = (prev[K] + (K > 0 ? curr[K - 1] : 0)) % mod;\n curr[K] = (curr[K] + mod - (K >= N ? prev[K-N] : 0)) % mod;\n }\n prev = curr;\n }\n return curr[k];\n }\n};\n```\n\n\n\n\nHope you found this helpful\nIf so please do Upvote it\nHappy Coding!!\n\n![leetcode.png](https://assets.leetcode.com/users/images/7a98ada3-fb9b-4413-8538-92fe790f4577_1701070150.1852815.png)\n\n
163
2
['Dynamic Programming', 'Memoization', 'C++']
8
k-inverse-pairs-array
K inverse pairs || C++ || dp || explained
k-inverse-pairs-c-dp-explained-by-aynbur-jvuf
Let\'s say we have n=4 with k not fixed;\nNow, see the steps \n1 2 3 4 => k = 0\n1 2 4 3 => k = 1\n1 4 2 3 => k = 2\n4 1 2 3 => k = 3\nThus we can observ
aynburnt
NORMAL
2021-06-19T12:20:32.236963+00:00
2021-06-19T12:21:43.997371+00:00
6,330
false
Let\'s say we have n=4 with k not fixed;\nNow, see the steps \n1 2 3 4 => k = 0\n1 2 4 3 => k = 1\n1 4 2 3 => k = 2\n4 1 2 3 => k = 3\nThus we can observe tha whenever we shift a greater number towards left k increases\ninfact k = no. of shift of a greater number towards left + prev_count;\ne.g shift 3 by two step left\n 4 3 1 2 => k = 2 + 3 = 5;\n \n Now its clear that we are using prev calculations to get the curr ans, leading towards DP; \n\nFirst look for 2D dp,\n1. If n=0, no inverse pairs exist. Thus, dp[0][k]=0.\n\n2. If k=0, only one arrangement is possible, which is all numbers sorted in ascending order. Thus, dp[n][0]=1.\n\n3. Otherwise, dp[i,j] = sum( for(p=0 to min(j, i-1) dp[i-1][j-p] ) )\n\nNow, in the 3rd step, in the loop every time we are just adding a value to right and removing a value from left \nThus our next optimization in this step =>\n\tdp[i][j] = d[i][j-1] + (dp[i-1][j-1] - (i>=j ? dp[i-1][j-i] : 0));\n\t\nNow we can do more optimization by the fact that we are using only two values from the prev row and thus need only prev row for calculations.\n\n```\nint kInversePairs(int n, int k) {\n vector<int> dp(k+1, 0);\n int mod = 1e9+7;\n for(int i=1; i<=n; i++){\n vector<int> tmp(k+1, 0);\n tmp[0] = 1;\n for(int j =1; j<=k; j++){\n long long val = (dp[j] + mod - ((j-i) >=0 ? dp[j-i] : 0))%mod;\n tmp[j] = (tmp[j-1] + val)%mod;\n }\n dp = tmp;\n }\n return (dp[k] + mod - (k>0 ? dp[k-1] : 0))%mod;\n }\n```\n# If you find it helpful, plz upvote;
82
3
['Dynamic Programming', 'C']
4
k-inverse-pairs-array
✅☑[C++/Java/Python/JavaScript] || EXPLAINED🔥
cjavapythonjavascript-explained-by-marks-vrks
PLEASE UPVOTE IF IT HELPED\n\n---\n\n\n# Approaches\n(Also explained in the code)\n\n1. Dynamic Programming:\n\n - Use a 2D array dp to store the number of a
MarkSPhilip31
NORMAL
2024-01-27T01:46:42.684983+00:00
2024-01-27T01:46:42.685004+00:00
20,787
false
# PLEASE UPVOTE IF IT HELPED\n\n---\n\n\n# Approaches\n(Also explained in the code)\n\n1. **Dynamic Programming:**\n\n - Use a 2D array `dp` to store the number of arrays with at most `k` inverse pairs for each size i and number of inverse pairs `j`.\nInitialize `dp[0][0]` to 1 as a base case.\n1. **Recurrence Relation:**\n\n - For each `i` and `j`, iterate over `x` to compute the number of arrays with at most `k` inverse pairs.\n - Update `dp[i][j]` based on the recurrence relation: `dp[i][j] = (dp[i][j] + dp[i - 1][j - x]) % 1000000007`.\n1. **Result:**\n\n - The final result is stored in `dp[n][k]`, representing the number of arrays with at most `k` inverse pairs for an array of size `n`.\n\n\n\n# Complexity\n- Time complexity:\n $$O(n*k^2)$$\n \n\n- Space complexity:\n $$O(n*k)$$\n \n\n\n# Code\n```C++ []\nclass Solution {\npublic:\n int kInversePairs(int n, int k) {\n int dp[1001][1001] = {1}; \n for (int i = 1; i <= n; i++) {\n for (int j = 0; j <= k; j++) {\n for (int x = 0; x <= min(j, i - 1); x++) {\n \n if (j - x >= 0) {\n dp[i][j] = (dp[i][j] + dp[i - 1][j - x]) % 1000000007;\n }\n }\n }\n }\n\n return dp[n][k];\n }\n};\n\n\n\n\n```\n```Java []\nclass Solution {\n public int kInversePairs(int n, int k) {\n int[][] dp = new int[1001][1001];\n dp[0][0] = 1;\n\n for (int i = 1; i <= n; i++) {\n for (int j = 0; j <= k; j++) {\n for (int x = 0; x <= Math.min(j, i - 1); x++) {\n if (j - x >= 0) {\n dp[i][j] = (dp[i][j] + dp[i - 1][j - x]) % 1000000007;\n }\n }\n }\n }\n\n return dp[n][k];\n }\n}\n\n\n\n```\n```python3 []\nclass Solution:\n def kInversePairs(self, n: int, k: int) -> int:\n dp = [[0] * 1001 for _ in range(1001)]\n dp[0][0] = 1\n\n for i in range(1, n + 1):\n for j in range(0, k + 1):\n for x in range(0, min(j, i - 1) + 1):\n if j - x >= 0:\n dp[i][j] = (dp[i][j] + dp[i - 1][j - x]) % 1000000007\n\n return dp[n][k]\n\n\n```\n\n```javascript []\nvar kInversePairs = function(n, k) {\n const M = 1000000007;\n let dp = new Array(1001).fill(0).map(() => new Array(1001).fill(0));\n dp[0][0] = 1;\n\n for (let i = 1; i <= n; i++) {\n for (let j = 0; j <= k; j++) {\n for (let x = 0; x <= Math.min(j, i - 1); x++) {\n if (j - x >= 0) {\n dp[i][j] = (dp[i][j] + dp[i - 1][j - x]) % M;\n }\n }\n }\n }\n\n return dp[n][k];\n};\n\n\n\n```\n---\n\n\n\n# PLEASE UPVOTE IF IT HELPED\n\n---\n---\n\n\n---
74
11
['Dynamic Programming', 'Python', 'C++', 'Java', 'Python3', 'JavaScript']
14
k-inverse-pairs-array
Python: Explained Bottom-Up DP
python-explained-bottom-up-dp-by-meadity-k5ag
Cases:\n1. We know that the bruteforce way to calculate the number of inversions takes O(n^2) time.\nAnd takes n(n-1)/2 comparisions. How?\n\nSuppose, arr = [1,
meaditya70
NORMAL
2021-06-19T11:58:06.422505+00:00
2021-06-19T12:37:32.436635+00:00
3,991
false
Cases:\n1. We know that the bruteforce way to calculate the number of inversions takes O(n^2) time.\nAnd takes n*(n-1)/2 comparisions. How?\n\nSuppose, arr = [1,3,2] and we count the number of inversions in the below given way\n```\ncount = 0\nfor i from 0 to n-2:\n for j from i to n-1:\n\t if arr[i]>arr[j]:\n\t\t count += 1\nreturn count\n```\nSo, here we compare indices [0,1],[0,2] and [1,2] which is equal to 3 comparisions (for n = 3, n*(n-1)/2 == 3).\nFor n=4, we compare indices [0,1],[0,2],[0,3],[1,2],[1,3],[2,3] == 6 comparisions = n * (n-1) / 2.\nI hope this is clear.\n\nNow, the maximum number of inversions for a n-sized array = n * (n-1) / 2\nSo, if K > n * (n-1) / 2, we cannot have any array with k number of inversions, so **return 0.**\nBut if k == 0 means no inversion, there is only **one possible way** to arrange the elements of array,i.e., sort in ascending order and get 0 inversions, so **return 1**. \nAlso, if k == n * (n-1)/2 means all possible inversions, and this can be achieved by **only one arrangement** of the array, i.e., sort in descending order and get max possible inversions, so **return 1**. \n\n\n*Now, it is time to create the DP array.*\n2. If n==0 : It means there are no numbers at all, so zero, for any value of k.\nAlso, If k==0, we have already discussed it above, that only 1 possible arrangement(ascending order sort). \nInitial DP Config.: Assume N = 3 and K = 4.\n![image](https://assets.leetcode.com/users/images/eb16bfd3-bd2a-404e-b0b8-e2c959b7b685_1624102962.3510895.png)\n\n\n\n3. For n = 2, we can have maximum n * (n-1)/2 = 1 inversion, i.e., [2,1]. So, lets fill it directly and avoid computation for n = 2 as there are only two possible cases of inversions, 0 -> no inversion, and 1 -> max inversion.\n4. Filling up the dp array.\n![image](https://assets.leetcode.com/users/images/45142fd4-dd7c-4374-9fa3-3bd3f117be70_1624103010.2909956.png)\nWe start filling the dp array using formula, from i = 3 onwards as upto 2 we have filled the dp array manually.\n\n**Note:** *It\'s really difficult to explain this problem. Kindly read the whole explanation, so that you get a feel of what is happening internally. Just read once briefly and then read again thoroughly, you will understand what i am trying to say, don\'t keep reading the same line again and again if you are not understanding it, move forward and ready once breifly till the end, then read again and I am sure you will get it. **The dp[3][3] will clear most of your confusion.*** So, be patient till then.\n\ndp[3][1] means array containing 1,2 and 3 with 1 number of inversions, so we can use dp[2,1] as we can add 3 at the end of the array [2, 1] and make **[2, 1, 3]** so we have 1 inversion and we can use the array [1,2] and add in the middle **[1,3,2]** to get 1 inversion, so total = 2 inversions = dp[i][j-1] + dp[i-1][j].\n\nFor, dp[3][2], we can use dp[2,2], i.e, zero arrangement and [1,2] and add 3 at the 0th index to make **[3,1,2]** and get 2 inversions and we can use [2,1] and add 3 in the middle to get **[2,3,1]** and have 2 inversions here as well, this two arrays comes from dp[3,1]. So total possibilities to arrange the array = 0 + 2 = 2.\n\nNow, for dp[3,3],\nwe can use dp[2,3] with zero arrangement, and we can use dp[3,2] but here is a catch. \nWhen we use dp[3,2] we are using arrays [1,2] and [2, 1] and when we want to insert 3 at -1 index of [1,2] it will be out of bound so we cannot use -1. Why -1? If you observe we are following a sequence, Initially we inserted 3 at the end of [1,2] to make [1,2,3] then we decremented the position and we get [1,3,2] followed by [3,1,2]. We are shifting 3 towards the left and now we don\u2019t have any more position to shift 3 so we cannot consider the array [1,2] but we can still consider [2,1] as previously 3 was in the middle and we had [2,3,1] we still have one more index to shift and we will get **[3,2,1]** with 3 inversions. Hence, only one arrangement possible, thus, dp[3][3] = 1.\n\nFormula for this is, when j >= i, along with doing dp[i][j] = dp[i-1][j] + dp[i][j-1] we also subtract dp[i-1][j-i] for the invalid shifting case.\n\nNow, dp[3,4] = 0, as max_possible_inversions = 3 * (3-1) /2 = 3, so we will have zero arrangement for 4 inversions.\n\n\n\n--------------------------------------------------------------------------------\n--------------------------------------------------------------------------------\n**EDIT:**\n\nThink this way, dp[3,0] came from dp[2,0] which was [1,2] by append 3 at the end of it and became [1,2,3].\nNow, dp[3,1] is coming from dp[3,0] by shifting 3 in [1,2,3] left once to make [1,3,2] and dp[3,1] is also coming from dp[2,1] by appending 3 to [2,1] which was not there earlier to make [2,1,3].\n\nSimilarly, dp[3,2] is coming from dp[3,1] by shifting 3 left once in both [1,3,2] and [2,1,3] to make [3,1,2] and [2,3,1] respectively and dp[3,2] is also coming from dp[2,2] but there is nothing in dp[2,2].\n\nI hope this makes it clear.\n\nNow, dp[3,3] is coming from dp[3,2] by shifting 3 left once in both [3,1,2] and [2,3,1] to make [3, - , 1, 2] (which is invalid) and [3,2,1] respectively. Now, we cannot consider the invalid case, so we need to remove it. So, we need to figure it out from where [3,1,2] came actually, it came from [1,2] which is dp[2,0] initially right, so we subtract dp[i-1][j-i].\n\n\n--------------------------------------------------------------------------------\n--------------------------------------------------------------------------------\n\n\nNow, you guys might be thinking how to solve this problem on our own without any help. \nHonestly, I have no idea. I myself took help from https://leetcode.com/problems/k-inverse-pairs-array/discuss/104815/Java-DP-O(nk)-solution and understood and solved. This was a really tough problem for me. And I tried to make it a little simple by some explanations. \n\nThe full code:\n```\nclass Solution:\n def kInversePairs(self, n: int, k: int) -> int:\n \n max_possible_inversions = (n * (n-1)//2)\n if k > max_possible_inversions:\n return 0\n if k == 0 or k == max_possible_inversions:\n return 1\n \n MOD = pow(10,9) + 7\n \n dp = [[0]*(k+1) for _ in range(n+1)]\n \n for i in range(1, n+1):\n dp[i][0] = 1\n\n dp[2][1] = 1\n \n for i in range(3,n+1):\n max_possible_inversions = min(k, i*(i-1)//2)\n for j in range(1, max_possible_inversions + 1):\n dp[i][j] = dp[i][j-1] + dp[i-1][j] \n if j>=i:\n dp[i][j] -= dp[i-1][j - i]\n dp[i][j] = (dp[i][j] + MOD) % MOD\n \n return dp[n][k]\n```\n\nTime = Space = O(n * k) owing to DP array.\n\nHope it helped!\n\n\n\n\n\n
72
2
['Dynamic Programming', 'Python']
7
k-inverse-pairs-array
Python, Straightforward with Explanation
python-straightforward-with-explanation-yorsl
Let's try for a top-down dp. Suppose we know dp[n][k], the number of permutations of (1...n) with k inverse pairs.\n\nLooking at a potential recursion for dp[n
awice
NORMAL
2017-06-25T03:41:22.901000+00:00
2017-06-25T03:41:22.901000+00:00
9,218
false
Let's try for a top-down dp. Suppose we know ```dp[n][k]```, the number of permutations of (1...n) with k inverse pairs.\n\nLooking at a potential recursion for ```dp[n+1][k]```, depending on where we put the element (n+1) in our permutation, we may add 0, 1, 2, ..., n new inverse pairs. For example, if we have some permutation of 1...4, then:\n* 5 x x x x creates 4 new inverse pairs\n* x 5 x x x creates 3 new inverse pairs\n* ...\n* x x x x 5 creates 0 new inverse pairs\n\nwhere in the above I'm representing any permutation of 1...4 with x's.\nThus, ```dp[n+1][k] = sum_{x=0..n} dp[n][k-x]```.\n\nThis dp has ```NK``` states with ```K/2``` work, which isn't fast enough. We need to optimize further.\n\nLet ```ds[n][k] = sum_{x=0..k-1} dp[n][x]```. \nThen ```dp[n+1][k] = ds[n][k+1] - ds[n][k-n]```,\nand the left hand side is ```ds[n+1][k+1] - ds[n+1][k]```.\nThus, we can perform all calculations in terms of ```ds```.\n\nFinally, to save space, we will only store the two most recent rows of ```ds```, using ```ds``` and ```new```.\n\nIn the code, we refer to ```-ds[n][k-n+1]``` instead of ```-ds[n][k-n]``` because the ```n``` being considered is actually n+1. For example, when ```n=2```, we are appending information about ```ds[2][k]``` to ```new```, so our formula of ```dp[n+1][k] = ds[n][k+1] - ds[n][k-n]``` is ```dp[2][k] = ds[1][k+1] - ds[1][k-1]```.\n\n```\ndef kInversePairs(self, N, K):\n MOD = 10**9 + 7\n ds = [0] + [1] * (K + 1)\n for n in xrange(2, N+1):\n new = [0]\n for k in xrange(K+1):\n v = ds[k+1]\n v -= ds[k-n+1] if k >= n else 0\n new.append( (new[-1] + v) % MOD )\n ds = new\n return (ds[K+1] - ds[K]) % MOD\n```
67
5
[]
4
k-inverse-pairs-array
Shared my C++ O(n * k) solution with explanation
shared-my-c-on-k-solution-with-explanati-09bd
For a better understanding, I would use O(n * k ) space instead of O(k) space. It's easy to write O(k) space version when you understand this DP process.\nAs @
yangyx
NORMAL
2017-06-25T09:14:07.512000+00:00
2017-06-25T09:14:07.512000+00:00
9,646
false
For a better understanding, I would use O(n * k ) space instead of O(k) space. It's easy to write O(k) space version when you understand this DP process.\nAs @awice said in his [Post ](https://discuss.leetcode.com/topic/93721/python-straightforward-with-explanation)\n> For example, if we have some permutation of 1...4\n>* 5 x x x x creates 4 new inverse pairs\n>* x 5 x x x creates 3 new inverse pairs\n...\n>* x x x x 5 creates 0 new inverse pairs\n\n### O(n * k ^ 2) Solution\nWe can use this formula to solve this problem\n```\ndp[i][j] //represent the number of permutations of (1...n) with k inverse pairs.\ndp[i][j] = dp[i-1][j] + dp[i-1][j-1] + dp[i-1][j-2] + ..... +dp[i-1][j - i + 1]\n```\nSo, We write a O(k*n^2) Solution through above formula like this \n```\npublic:\n int kInversePairs(int n, int k) {\n vector<vector<int>> dp(n + 1, vector<int>(k+1, 0));\n dp[0][0] = 1;\n for(int i = 1; i <= n; ++i){\n for(int j = 0; j < i; ++j){ // In number i, we can create 0 ~ i-1 inverse pairs \n for(int m = 0; m <= k; ++m){ //dp[i][m] += dp[i-1][m-j]\n if(m - j >= 0 && m - j <= k){\n dp[i][m] = (dp[i][m] + dp[i-1][m-j]) % mod; \n }\n }\n }\n }\n return dp[n][k];\n }\nprivate:\n const int mod = pow(10, 9) + 7;\n};\n```\nBut the above solution is too slow, it spends 1000+ms\n\n### O(n * l) Solution\nLook back to the above formula.\n\n`dp[i][j] = dp[i-1][j] + dp[i-1][j-1] + dp[i-1][j-2] + ..... +dp[i-1][j - i + 1]`\nLet's consider this example\nif `i = 5 `\n```\ndp[i][0] = dp[i-1][0] (creates 0 inverse pair)\ndp[i][1] = dp[i-1][0] (1) + dp[i-1][1] (0) = dp[i][0] + dp[i-1][1]\ndp[i][2] = dp[i-1][0] (2) + dp[i-1][1] (1) + dp[i-1][2] (0) = dp[i][1] + dp[i-1][2]\n.\n.\n.\ndp[i][4] = dp[i-1][0] (4) + dp[i-1][1] (3) + dp[i-1][2] (2) + dp[i-1][3] (1) + dp[i-1][4] (0) = dp[i][3] + dp[i-1][4]\n```\nCan you find the rules about above formula. \nif `j < i` , we can compute `dp[i][j] = dp[i][j-1] +dp[i-1][j]`\n\nSo, how about `j >= i`\nWe know if we add number i into permutation(0 .. i -1 ), i can create 0 ~i -1 inverse pair\nIf `j >= i` , we still use `dp[i][j] = dp[i][j-1] +dp[i-1][j]`.\nWe must minus `dp[i][j-i]`. (In fact it minus` dp[i-1][j-i]`, because every` j >= i `in dp vecor,it minus `dp[i-1][j-i] `individually)\nFor example, if `i = 5`\n\n`dp[i][5] = dp[i][4] + dp[i-1][5] - dp[i-1][0]`\n`dp[i][6] = dp[i][5] + dp[i-1][6] - dp[i-1][1]`\n\nreference code\n```\nclass Solution {\npublic:\n int kInversePairs(int n, int k) {\n vector<vector<int>> dp(n+1, vector<int>(k+1));\n dp[0][0] = 1;\n for(int i = 1; i <= n; ++i){\n dp[i][0] = 1;\n for(int j = 1; j <= k; ++j){\n dp[i][j] = (dp[i][j-1] + dp[i-1][j]) % mod;\n if(j - i >= 0){\n dp[i][j] = (dp[i][j] - dp[i-1][j-i] + mod) % mod; \n //It must + mod, If you don't know why, you can check the case 1000, 1000\n }\n }\n }\n return dp[n][k];\n }\nprivate:\n const int mod = pow(10, 9) + 7;\n};\n```
60
2
[]
9
k-inverse-pairs-array
4-term recurrence Mahonian numbers||DP O(nk) 6 ms Beats 87.36%
4-term-recurrence-mahonian-numbersdp-onk-sse4
Intuition\n Describe your first thoughts on how to solve this problem. \nDerive the 4-term recurrence for Triangle of Mahonian numbers \n\n(A):f(n, k) = f(n-1,
anwendeng
NORMAL
2024-01-27T01:27:38.713842+00:00
2024-01-27T23:00:25.270019+00:00
4,595
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nDerive the 4-term recurrence for Triangle of Mahonian numbers \n$$\n(A):f(n, k) = f(n-1, k) + f(n-1, k-1) + f(n-1, k-2) +\\cdots+ f(n-1, k-n+1)\\\\ \n(B):f(n, k-1) = f(n-1, k-1) + f(n-1, k-2) + f(n-1, k-3) +\\cdots + f(n-1, k-n+1)+ f(n-1, k-n) \n$$\n(A)-(B) follows\n$$\n\\implies f(n, k) =f(n-1, k)+f(n, k-1)-f(n-1, k-n)\n$$\nIf you feel hard to simplify formula, think about prefix sums, it will help.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n[Please turn English subtitles if necessary]\n[https://youtu.be/gsJs1MEONuk?si=I5dGgCKZaohV7dPX](https://youtu.be/gsJs1MEONuk?si=I5dGgCKZaohV7dPX)\nReference: https://oeis.org/A008302\nFind the suitable Math formula, then begin to program! Let\'s see some properties:\n __Fact 0__ $f(n, 0)=1$ (Base case). $f(n, k)=0$ if $n\\leq 0$ or$ k<0$ except for $(n, k)=(0, 0)$. \n __Fact 1__ $ f(n, k)=\\sum_{j=0}^{n-1}f(n-1, k-j)$\n_Proof sketch._ Put the $i$-th max element in the last position.\nWhen the the first $n-1$ elements have $k-i$ inversions, there are $k$ inversions in this case. __Q.E.D__\n__Fact 2__ $f(n, k)=f(n, C^n_2-k)$\n__Theorem__ $f(n, k) =f(n-1, k)+f(n, k-1)-f(n-1, k-n)$\n\nIterative DP is made with optimized space $O(k)$ by using `&1` trick.\n\n# Triangle Mahhonian numbers up to n=6\nOutput from my DP code with modification\n```\n k: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15\nn= 0: 1\nn= 1: 1\nn= 2: 1 1\nn= 3: 1 2 2 1\nn= 4: 1 3 5 6 5 3 1\nn= 5: 1 4 9 15 20 22 20 15 9 4 1\nn= 6: 1 5 14 29 49 71 90 101 101 90 71 49 29 14 5 1\n```\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(nk)$$\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(nk)\\to O(k)$$\n# Code\n\n```python []\nclass Solution:\n def kInversePairs(self, n: int, k: int) -> int:\n @cache\n def f(n, k):\n if k==0: return 1\n if k<0 or n<=0: return 0\n return (f(n-1, k)+f(n, k-1)-f(n-1, k-n)+10**9+7)%(10**9+7)\n return f(n, k)\n```\n```C++ []\n#pragma GCC optimize("O3", "unroll-loops")\nclass Solution {\npublic:\n int dp[1001][1001];\n int mod=1e9+7;\n long long f(int n, int k){\n if (k==0) return 1;\n if (k<0 || n<=0) return 0;\n if(dp[n][k]!=-1) return dp[n][k];\n return dp[n][k]=(f(n-1, k)+f(n, k-1)-f(n-1, k-n)+mod)%mod;\n }\n int kInversePairs(int n, int k) {\n memset(dp, -1, sizeof(dp));\n return f(n, k);\n }\n};\n\n```\n# C++ iterative DP with optimized space||6 ms Beats 87.36%\n```\n#pragma GCC optimize("O3", "unroll-loops")\nclass Solution {\npublic:\n int kInversePairs(int n, int k) {\n k=min(k, n*(n-1)/2-k);//Use Fact 2\n if (k<0) return 0;\n long long dp[2][1001]={0};\n dp[0][0]=1;\n long long mod=1e9+7;\n for(int i=1; i<=n; i++){\n dp[i&1][0]=1;\n long long x=0;\n for(int j=1; j<=k; j++){//Use Theorem\n x=dp[(i-1)&1][j]+dp[i&1][j-1];\n if (j-i>=0) \n x+=(mod-dp[(i-1)&1][j-i]);\n dp[i&1][j]=x%mod;\n }\n }\n return dp[n&1][k];\n }\n};\n\nauto init = []()\n{ \n ios::sync_with_stdio(0);\n cin.tie(0);\n cout.tie(0);\n return \'c\';\n}();\n\n```\n
53
5
['Math', 'Dynamic Programming', 'Memoization', 'C++', 'Python3']
7
k-inverse-pairs-array
[Python] Short O(nk) solution, explained
python-short-onk-solution-explained-by-d-1z70
Let dp[i][j] be number of permutation of numbers [1, ..., i], such that it has exactly j inverses. Then we can show, that:\n\ndp[i][j] = dp[i-1][j] + dp[i-1][j-
dbabichev
NORMAL
2021-06-19T07:19:52.513917+00:00
2021-06-19T07:19:52.513995+00:00
2,553
false
Let `dp[i][j]` be number of permutation of numbers `[1, ..., i]`, such that it has exactly `j` inverses. Then we can show, that:\n\n`dp[i][j] = dp[i-1][j] + dp[i-1][j-1]+ ... + dp[i-1][j-i+1]`,\nbecause we can insert number `i` in `i` different places. Note that if `j-i+1 < 0`, than we need to stop at `dp[i-1][0]`. Let as also introduce cumulative sums `sp[i][j] = dp[i][0] + ... + dp[i][j]`, then we can do updates in `O(1)`. Note also starting values `dp[i][0] = 1`, because there is exactly one permutation: constant permutation with zero inverses. Also `sp[i][0] = 1`. It does not matter what we put in other cells, because we are going to change them, so we fill everything with `1`.\n\n#### Complexity\nWe have `O(nk)` time and space complexity.\n\n#### Code\n```python\nclass Solution:\n def kInversePairs(self, n, k):\n dp = [[1] * (k+1) for _ in range(n+1)]\n sp = [[1] * (k+1) for _ in range(n+1)]\n N = 10**9 + 7\n\n for i in range(1, n+1):\n for j in range(1, k+1):\n dp[i][j] = sp[i-1][j] if j < i else (sp[i-1][j] - sp[i-1][j-i]) % N\n sp[i][j] = (sp[i][j-1] + dp[i][j]) % N\n \n return dp[-1][-1]\n```\n\n#### Remark\nActually, we can get rid off `sp` and use only `dp`, if we write down equation for `dp[i][j]` and `dp[i][j+1]` and subtract them. Also memory can be reduced to `O(k)`.\n\nIf you have any question, feel free to ask. If you like the explanations, please **Upvote!**
52
1
['Dynamic Programming']
3
k-inverse-pairs-array
Easily DP Explained🔥 | C++✔ | Java✔ | Python ✔|
easily-dp-explained-c-java-python-by-rec-a4mf
If you like the solution please give it a upvote \uD83D\uDE22\n# Intuition\nTo solve this problem, we can use dynamic programming to keep track of the number of
Recode_-1
NORMAL
2024-01-27T02:59:18.740455+00:00
2024-01-27T02:59:18.740483+00:00
11,715
false
# If you like the solution please give it a upvote \uD83D\uDE22\n# Intuition\nTo solve this problem, we can use dynamic programming to keep track of the number of arrays with a certain number of inverse pairs. By iteratively calculating this for increasing array sizes, we can find the total number of arrays with exactly k inverse pairs.\n\n\n\n# Approach\n1. DP Array: We `create a 2D array dp`, where `dp[i][j] represents the number of arrays with i elements and j inverse pairs`.\n\n2. Filling the DP Array:\n\n - We start with an array of size 1, which has 0 inverse pairs, so dp[1][0] = 1.\n\n ```\n if (j == 0) {\n dp[i][j] = 1;\n }\n ```\n - We then consider arrays of size 2, 3, and so on, up to n.\n - For each array size i, we calculate the number of inverse pairs j from 0 to k.\n ```\n int val = (dp[i - 1][j] + MOD - (j - i >= 0 ? dp[i - 1][j - i] : 0)) % MOD;\n ```\n - Or We can also write this line as below for understanding \n ```\n int previous = dp[i - 1][j]; // Count of arrays with (i - 1) elements and j inverse pairs\n\n int subtracted = 0;\n if (j - i >= 0) {\n subtracted = dp[i - 1][j - i]; // Count of arrays with (i - 1) elements and (j - i) inverse pairs\n }\n\n int adjusted = (previous + MOD - subtracted) % MOD; // Adjusted count to consider negative values\n\n int val = adjusted; // Final value for dp[i][j]\n ``` \n - We fill in dp[i][j] based on the counts we\'ve already calculated for smaller array sizes.\n\n3. Updating Counts:\n\n - To calculate dp[i][j], we consider two cases:\n - If j is 0, there\'s only one way to arrange the array, so we set dp[i][0] to 1.\n - Otherwise, we calculate dp[i][j] based on the counts of inverse pairs in arrays of size i-1.\n# Complexity\n- Time complexity: `O(n\xD7k)`\n\n- Space complexity: `O(n\xD7k)`\n\n# Code\n```\n#include <vector>\n\nclass Solution {\npublic:\n int kInversePairs(int n, int k) {\n const int MOD = 1000000007;\n std::vector<std::vector<int>> dp(n + 1, std::vector<int>(k + 1, 0));\n\n for (int i = 1; i <= n; ++i) {\n for (int j = 0; j <= k; ++j) {\n if (j == 0) {\n dp[i][j] = 1;\n } else {\n int val = (dp[i - 1][j] + MOD - (j - i >= 0 ? dp[i - 1][j - i] : 0)) % MOD;\n dp[i][j] = (dp[i][j - 1] + val) % MOD;\n }\n }\n }\n\n return (dp[n][k] + MOD - (k > 0 ? dp[n][k - 1] : 0)) % MOD;\n }\n};\n\n```\n# Java \n```\nclass Solution {\n public int kInversePairs(int n, int k) {\n final int MOD = 1000000007;\n int[][] dp = new int[n + 1][k + 1];\n\n for (int i = 1; i <= n; ++i) {\n for (int j = 0; j <= k; ++j) {\n if (j == 0) {\n dp[i][j] = 1;\n } else {\n int val = (dp[i - 1][j] + MOD - (j - i >= 0 ? dp[i - 1][j - i] : 0)) % MOD;\n dp[i][j] = (dp[i][j - 1] + val) % MOD;\n }\n }\n }\n\n return (dp[n][k] + MOD - (k > 0 ? dp[n][k - 1] : 0)) % MOD;\n }\n}\n\n```\n# Python\n```\nclass Solution:\n def kInversePairs(self, n: int, k: int) -> int:\n MOD = 10**9 + 7\n dp = [[0] * (k + 1) for _ in range(n + 1)]\n\n for i in range(1, n + 1):\n for j in range(k + 1):\n if j == 0:\n dp[i][j] = 1\n else:\n val = (dp[i - 1][j] + MOD - (dp[i - 1][j - i] if j - i >= 0 else 0)) % MOD\n dp[i][j] = (dp[i][j - 1] + val) % MOD\n\n return (dp[n][k] + MOD - (dp[n][k - 1] if k > 0 else 0)) % MOD\n\n```
51
0
['Dynamic Programming', 'Python', 'C++', 'Java', 'Python3']
6
k-inverse-pairs-array
Python concise solution
python-concise-solution-by-lee215-iwcr
\nf(n,k) = sum(f(n-1,i)), where max(k-n+1,0) <= i <= k\nf(0,k) = 0\nf(n,0) = 1\n`````\n\ndef kInversePairs(self, n, k):\n dp = [1] + [0] * k\n for
lee215
NORMAL
2017-06-28T18:45:31.044000+00:00
2017-06-28T18:45:31.044000+00:00
4,617
false
````\nf(n,k) = sum(f(n-1,i)), where max(k-n+1,0) <= i <= k\nf(0,k) = 0\nf(n,0) = 1\n`````\n````\ndef kInversePairs(self, n, k):\n dp = [1] + [0] * k\n for i in range(2, n + 1):\n for j in range(1, k + 1): dp[j] += dp[j - 1]\n for j in range(k, 0, -1): dp[j] -= j - i >= 0 and dp[j - i]\n return dp[k] % (10**9 + 7)
40
8
[]
3
k-inverse-pairs-array
Easy || Recursion || Memoization || Tabulation || Explained with comments
easy-recursion-memoization-tabulation-ex-jaso
I have explained all the approaches.\nIf you have any doubts then let me know in comments.\n\nUnderstand it before copying and Plz Upvote It motivates me to w
ankit6378yadav
NORMAL
2022-07-17T12:11:41.605269+00:00
2022-07-17T12:11:41.605302+00:00
3,627
false
I have explained all the approaches.\nIf you have any doubts then let me know in comments.\n\nUnderstand it before copying and **Plz Upvote** It motivates me to write these answers.\n\n**First the recursive approach:**\nIt will give TLE\n```\nclass Solution {\npublic:\n int mod = (int)(1e9 + 7);\n int dp[1001][1001] = {};\n \n int kInversePairs(int n, int k) {\n //base case\n if(k<=0) return k==0;\n \n if(dp[n][k]==0){\n dp[n][k] = 1;\n \n for(int i=0; i<n; i++){\n dp[n][k] = (dp[n][k] + kInversePairs(n-1,k-i))%mod;\n }\n }\n return dp[n][k]-1;\n }\n};\n```\n**Tabulation**\n```\nclass Solution {\npublic:\n int kInversePairs(int n, int k) {\n int dp[1001][1001] = { 1 };\n \n for(int i=1;i<=n;++i)\n for(int K=0; K<=k;++K)\n for(int j=0; j<= min(K,i-1);++j)\n dp[i][K] = (dp[i][K] + dp[i-1][K-j])%1000000007;\n return dp[n][k];\n }\n};\n```\n**Memoization Approach**\n```\nclass Solution {\npublic:\n int mod = (int)(1e9 + 7);\n \n int f(int n, int k, vector<vector<int>>& dp){\n //base case\n if(k<=0) return k==0;\n if(n<=0) return 0;\n \n //memoization\n if(dp[n][k]!=-1) return dp[n][k];\n \n \n dp[n][k] = (f(n-1, k, dp) + f(n, k-1, dp))%mod;\n \n return dp[n][k] = (dp[n][k] - f(n-1, k-n, dp) + mod)%mod;\n }\n int kInversePairs(int n, int k) {\n //Initialization of dp\n vector<vector<int>> dp(n+1,vector<int>(k+1,-1));\n return f(n,k,dp);\n }\n};\n```\n**Please Upvote!!**
39
10
['Dynamic Programming', 'Recursion', 'Memoization', 'C']
4
k-inverse-pairs-array
DP explained with figures [Python]
dp-explained-with-figures-python-by-bkch-51dr
[Observation 1]\nGiven any array of length n which contains m pairs, adding the (n+1)th number to the array can give the following results.\n\n\n## [Remark 1]\n
bkchang8
NORMAL
2022-07-17T04:55:50.452778+00:00
2022-07-17T21:00:20.616519+00:00
1,930
false
## [Observation 1]\nGiven any array of length `n` which contains `m` pairs, adding the `(n+1)th` number to the array can give the following results.\n![image](https://assets.leetcode.com/users/images/1ab3d724-9af2-4002-bfa5-6e8f441a195d_1658030805.9050553.jpeg)\n\n## [Remark 1]\nGiven an array of length `n` with `m` pairs, inserting the `(n+1)th` element at position `p` will result in a new array of length `n+1` with `m+(n-p+1)` pairs\n\n## [Observation 2]\nQ: How to construct an array of length `n` with `i` pairs?\nA1: IF we know the arrays of length `n-1` with `i` pairs, we just add the `(n)th` element to the end of those arrays\nA2: IF we know the arrays of length `n-1` with `i-1` pairs, we just insert the `(n)th` element to the `(n-1)th` position of those arrays\nA3: IF we know the arrays of length `n-1` with `i-2` pairs, we just insert the `(n)th` element to the `(n-2)th` position of those arrays\n...\n...\n\n## [Remark 2]\nDenote `(n, k)` the number of arrays with length `n` that contains `k` pairs, then \n`(n, k) = (n-1, k) + (n-1, k-1) + (n-1, k-2) + ... + (n-1, k-min(n, k))`. \nWe therefore find the subproblem between `n-1` and `n`. This problem can therefore be solved with dp.\n\n## [Strategy]\nWe scan from `1` to `n`, adding the elements one-by-one, and at each element `j`, we keep track of the #arrays (of length `j`) that contains `i` pairs (`i=0,1,2,...,k`). We only need to keep track of arrays that contains less than or equal to `k` pairs, since arrays with more than `k` pairs are not of our interest, and adding more elements later won\'t reduce the pairs that are already existing.\n\n## [Visualization]\nBelow I use `n=5` and `k=4` to illustrate what is going on in this algorithm. We use a `count` array of length `k+1` to keep track of the number of arrays that contain 0, 1, 2, 3, and 4 pairs obtained from the previous element. I specifically plot the sliding window summation lines for `count[2]` and `count[4]` for better illustration\n\n![image](https://assets.leetcode.com/users/images/3db374f3-25d9-4584-a18a-e4b22feb1d70_1658073061.0644476.jpeg)\n\nIn practice, at each run `n`, the summations needed to obtain `count[i-1]` and `count[i]` always have some overlap, so we use yet another layer of dp to do these sums, which, compared to the first dp, should be trivial.\n\n## [Code]\n```\nclass Solution:\n def kInversePairs(self, n: int, k: int) -> int:\n if k == 0 : return 1\n count = [1] + [0 for x in range(k)]\n for j in range(1, n):\n new_count = [1] + [0 for x in range(k)]\n tmp = 1\n for i in range(1, k+1):\n tmp += count[i]\n if i >= j+1:\n tmp -= count[i-j-1] \n new_count[i] = tmp\n count = new_count\n return count[-1] % (10**9+7)\n```\nSpace O(k), time O(n\\*k).
32
0
['Dynamic Programming', 'Sliding Window', 'Python']
4
k-inverse-pairs-array
[JAVA] DP || Detailed Explanation || Easy to Understand || Clean Code with Comments
java-dp-detailed-explanation-easy-to-und-kfpr
The difficulty of this question is how to find the relationship between the big problem and the sub-problems.\nI\'m sure many of us think about dynamic programm
angzhanh
NORMAL
2022-07-17T04:57:59.557028+00:00
2022-07-17T05:03:55.215253+00:00
2,859
false
The difficulty of this question is how to find the relationship between the big problem and the sub-problems.\nI\'m sure many of us think about dynamic programming but fail to find the inner relationship.\nLet us consider this question step by step. For a given k, when we get a new numebr n, we have lots of position to put it.\n1. If we put it in the last position, we can get `dp[n - 1][k]` inverse pairs.\n2. If we put it in the second last position, we can get `dp[n - 1][k - 1]` inverse pairs, since n is bigger than the number in the last position.\n3. ...\n4. If we put it in the first position, we can get `dp[n - 1][k - n + 1]` inverse pairs.\n\nSo, we get the relationship!\n`dp[n][k] = dp[n - 1][k] + dp[n - 1][k - 1] + ... + dp[n - 1][k - n + 1]`\n\nLet `dp[n][k]` minus `dp[n][k - 1]`, we can get the formula: \n`dp[n][k] = dp[n][k - 1] + dp[n - 1][k] - dp[n - 1][k - n]`\n\nNow we figure out it~\n```\nclass Solution {\n public int kInversePairs(int n, int k) {\n if (k > n * (n - 1) / 2) // n numbers can generate at most n * (n - 1) / 2 inverse pairs\n return 0;\n \n if (k == n * (n - 1) / 2 || k == 0)\n return 1;\n \n int mod = 1000000007;\n int[][] dp = new int[n + 1][k + 1];\n \n for (int i = 1; i < n + 1; i++) {\n dp[i][0] = 1; // deal with j = 0\n for (int j = 1; j < Math.min(k, i * (i - 1) / 2) + 1; j++) {\n dp[i][j] = (dp[i][j - 1] + dp[i - 1][j] - (j >= i ? dp[i - 1][j - i] : 0)) % mod;\n // all dp[i][j] modulo 10^9 + 7\n // so dp[i - 1][j - 1] might bigger than dp[i][j - 1] + dp[i - 1][j]\n if (dp[i][j] < 0) \n dp[i][j] += mod;\n }\n }\n \n return dp[n][k];\n }\n}\n```\nPlease vote if it helps\uD83D\uDE06~
30
0
['Dynamic Programming', 'Java']
5
k-inverse-pairs-array
Simple and Easy | DP | C++
simple-and-easy-dp-c-by-vian1608-m6jw
```\nconst int mod = 1e9 + 7, N = 1010;\n\nclass Solution {\n int f[N][N] = {};\npublic:\n int kInversePairs(int n, int K) {\n f[0][0] = 1;\n
vian1608
NORMAL
2022-07-17T00:18:04.689255+00:00
2022-07-17T00:18:04.689285+00:00
5,131
false
```\nconst int mod = 1e9 + 7, N = 1010;\n\nclass Solution {\n int f[N][N] = {};\npublic:\n int kInversePairs(int n, int K) {\n f[0][0] = 1;\n for (int i = 1; i <= n; ++ i) // 1000\n {\n long long s = 0; // maintain a window that is length min(i, j);\n for (int j = 0; j <= K; ++ j) // 1000\n {\n s += f[i - 1][j];\n if (j >= i)\n s -= f[i - 1][j - i];\n f[i][j] = ((long long)f[i][j] + s) % mod; \n }\n }\n return f[n][K];\n }\n};
29
4
['Dynamic Programming', 'C']
0
k-inverse-pairs-array
Recursive & Dp Approach - Simple Explanation || CPP
recursive-dp-approach-simple-explanation-7var
Upvote this solution\n\n\nError : -\n! At N = 4 and K = 2 -> There is 1 3 4 2 instead of 1 4 3 2 . \n! It is i = 0 to N\n\nThis is the recursive approach\nCODE:
AasthaChaudhary
NORMAL
2022-07-17T05:30:37.658983+00:00
2022-07-17T09:29:54.496872+00:00
3,619
false
# Upvote this solution\n\n![image](https://assets.leetcode.com/users/images/2c20cd61-30aa-4a1c-9f74-1f395791cdce_1658030956.758635.png)\n**Error : -\n! At N = 4 and K = 2 -> There is 1 3 4 2 instead of 1 4 3 2 . \n! It is i = 0 to N**\n\n**This is the recursive approach**\nCODE:\n```\nclass Solution {\n int v[1001][1001] = {0};\n int mod = 1000000007;\npublic:\n int kInversePairs(int n, int k) {\n if(n==0 || k<0)return 0;\n if ( k==0)return 1;\n if(v[n][k]==0){\n for(auto i = 0 ; i<=min(n-1,k) ; i++){\n v[n][k] = (v[n][k]+ kInversePairs(n-1,k-i))%mod;\n }\n }\n return v[n][k];\n }\n};\n```\n**This will gives you TLE**\n\nApproach - 2 -> Dyanmmic Programming\n```\nclass Solution {\npublic:\n int kInversePairs(int n, int k) {\n int dp[1001][1001] = {};\n for(int i = 1 ; i<= n ;i++){\n for(int j = 0 ; j<=k ; j++){\n if(j==0)dp[i][j]=1;\n else{\n for(int p = 0 ; p<=min(i-1,j);p++){\n dp[i][j] = (dp[i][j]+dp[i-1][j-p])%1000000007;\n }\n }\n }\n }\n return dp[n][k];\n }\n};\n```
26
2
['Dynamic Programming', 'Recursion', 'C++']
4
k-inverse-pairs-array
Python3 || dp, 1D array, 10 lines, w/ explanation || T/S: 95% / 86%
python3-dp-1d-array-10-lines-w-explanati-vtp3
The code below uses two 1D arrays--dp and tmp--instead if a 2D array. Note that tmp replaces dp after each i-iteration.\n\nclass Solution:\n def kInversePair
Spaulding_
NORMAL
2022-07-17T05:06:45.923962+00:00
2024-06-18T15:12:10.273161+00:00
1,304
false
The code below uses two 1D arrays--`dp` and `tmp`--instead if a 2D array. Note that `tmp` replaces `dp` after each i-iteration.\n```\nclass Solution:\n def kInversePairs(self, n: int, k: int) -> int:\n\n dp, mod = [1]+[0] * k, 1_000_000_007\n \n for i in range(n):\n tmp, sm = [], 0\n\n for j in range(k + 1):\n sm+= dp[j]\n if j-i >= 1: sm-= dp[j-i-1]\n sm%= mod\n tmp.append(sm)\n\n dp = tmp\n\n #print(dp) # <-- uncomment this line to get a sense of dp from the print output\n\t\t\t # try n = 6, k = 4; your answer should be 49.\n return dp[k]\n```\n[https://leetcode.com/problems/k-inverse-pairs-array/submissions/1157862002/](https://leetcode.com/problems/k-inverse-pairs-array/submissions/1157862002/)\n\n\n\n
20
0
['Python', 'Python3']
0
k-inverse-pairs-array
C++ | Cleanest code | Easy to understand
c-cleanest-code-easy-to-understand-by-ge-7o49
Do upvote\u2764,if you found it useful.\n\nclass Solution {\npublic:\n int mod=1e9+7;\n int kInversePairs(int n, int K) {\n //dp[i][j] denote till
GeekyBits
NORMAL
2022-07-17T05:41:27.754909+00:00
2022-07-17T18:19:05.429012+00:00
1,602
false
Do upvote\u2764,if you found it useful.\n```\nclass Solution {\npublic:\n int mod=1e9+7;\n int kInversePairs(int n, int K) {\n //dp[i][j] denote till i numbers how many jth inversion pair-containing permutations are there\n vector<vector<int>> dp(n+1,vector<int>(K+1,0));\n dp[0][0]=0;\n for(int i=1;i<=K;i++){\n dp[1][i]=0;\n }\n for(int i=1;i<=n;i++){\n dp[i][0]=1;\n }\n //now lets say we have N-1 numbers and K inversions and we are adding N to these N-1 numbers\n //if we add N to the end of the array,no increase in inversions will occur eg ****5\n //if we add N to the last second postiion of the array 1 inversion will increase so we will tell the remaining N-1 integers to rearrange them \n\t\t//in such a way that they produce K-1 inversions among themselves because I am contributing 1 inversion by being at the second last postiion\n\t\t//eg:***5*(1 inversion increased)\n //similarly ,if we put N to the last third position we will get our answer in dp[N-1][K-2] eg:**5**(2 inversions increased)\n //so basically dp[N][K]=dp[N-1][K]+dp[N-1][K-1]+dp[N-1][k-2]+dp[N-1][k-3]+.......dp[N-1][K-(N-1)];\n //also provided K-(N-1)>=0 at the end in the last term in the formula\n \n //but this will give tle\n //the code will be like\n /*\n for(int i=2;i<=n;i++){\n for(int j=1;j<=k;j++){\n for(int k=0;k<=i-1;k++){\n if(j-k>=0){\n dp[i][j]+=d[i][j-k];\n dp[i][j]%=mod;\n }\n }\n }\n }\n return dp[N][K];\n */\n //now see the **optimization**\n /*\n\t\tLets say we consider dp[4][6] and dp[4][7],just randomly\n\t\tAplly the formula above,and we will get\n dp[4][6]=dp[3][6]+dp[3][5]+dp[3][4]+dp[3][3]--------------------->(1)\n \n dp[4][7]=dp[3][7]+dp[3][6]+dp[3][5]+dp[3][4]---------------------->(2)\n \n //suntract 1 from 2\n dp[4][7]-dp[4][6]=dp[3][7]-dp[3][3]\n dp[4][7]=dp[4][6]+dp[3][7]-dp[3][3]\n //so dp[N][K]=dp[N-1][K]+dp[N][K-1]-dp[N-1][K-N]\n */\n for(int i=2;i<=n;i++){\n for(int j=1;j<=K;j++){\n dp[i][j]=(dp[i-1][j]+dp[i][j-1])%mod;\n if(j-i>=0){\n dp[i][j]=(dp[i][j]-dp[i-1][j-i]+mod)%mod;\n }\n } \n }\n return dp[n][K];\n }\n};\n```
19
0
[]
1
k-inverse-pairs-array
🔥 BEATS 100% | ✅ [ Py /Java / C++ / C / C# / JS / GO / Rust ]
beats-100-py-java-c-c-c-js-go-rust-by-ne-q2j0
\nPython []\nclass Solution:\n def kInversePairs(self, n: int, k: int) -> int:\n MOD = 1000000007\n dp = [0] * (k + 1)\n dp[0] = 1\n
Neoni_77
NORMAL
2024-01-27T06:10:08.102481+00:00
2024-08-08T17:49:22.962880+00:00
2,340
false
\n```Python []\nclass Solution:\n def kInversePairs(self, n: int, k: int) -> int:\n MOD = 1000000007\n dp = [0] * (k + 1)\n dp[0] = 1\n for i in range(2, n + 1):\n for j in range(1, k + 1):\n dp[j] = (dp[j] + dp[j - 1]) % MOD\n for j in range(k, i - 1, -1):\n dp[j] = (dp[j] - dp[j - i] + MOD) % MOD\n return dp[k]\n\n```\n```Java []\npublic class Solution {\n public int kInversePairs(int n, int k) {\n int MOD= 1000000007;\n int[] dp = new int[k+1];\n dp[0] = 1;\n for(int i = 2;i <= n;i++){\n for(int j = 1;j <= k;j++){\n dp[j] = (dp[j] + dp[j-1]) % MOD;\n }\n for(int j = k;j >= i;j--){\n dp[j] = (dp[j] - dp[j-i] + MOD) % MOD;\n }\n }\n return dp[k];\n }\n}\n```\n```C++ []\nclass Solution {\npublic:\n int kInversePairs(int n, int k) {\n int MOD = 1000000007;\n vector<int> dp(k + 1);\n dp[0] = 1;\n for (int i = 2; i <= n; i++) {\n for (int j = 1; j <= k; j++) {\n dp[j] = (dp[j] + dp[j - 1]) % MOD;\n }\n for (int j = k; j >= i; j--) {\n dp[j] = (dp[j] - dp[j - i] + MOD) % MOD;\n }\n }\n return dp[k];\n }\n};\n\n```\n```C []\nint kInversePairs(int n, int k) {\n int MOD = 1000000007;\n int dp[k + 1];\n dp[0] = 1;\n for (int i = 2; i <= n; i++) {\n for (int j = 1; j <= k; j++) {\n dp[j] = (dp[j] + dp[j - 1]) % MOD;\n }\n for (int j = k; j >= i; j--) {\n dp[j] = (dp[j] - dp[j - i] + MOD) % MOD;\n }\n }\n return dp[k];\n}\n\n```\n```C# []\npublic class Solution {\n public int KInversePairs(int n, int k) {\n int MOD = 1000000007;\n int[] dp = new int[k + 1];\n dp[0] = 1;\n for (int i = 2; i <= n; i++) {\n for (int j = 1; j <= k; j++) {\n dp[j] = (dp[j] + dp[j - 1]) % MOD;\n }\n for (int j = k; j >= i; j--) {\n dp[j] = (dp[j] - dp[j - i] + MOD) % MOD;\n }\n }\n return dp[k];\n }\n}\n\n```\n```Javascript []\n/**\n * @param {number} n\n * @param {number} k\n * @return {number}\n */\nvar kInversePairs = function(n, k) {\n const MOD = 1000000007;\n let dp = new Array(k + 1).fill(0);\n dp[0] = 1;\n for (let i = 2; i <= n; i++) {\n for (let j = 1; j <= k; j++) {\n dp[j] = (dp[j] + dp[j - 1]) % MOD;\n }\n for (let j = k; j >= i; j--) {\n dp[j] = (dp[j] - dp[j - i] + MOD) % MOD;\n }\n }\n return dp[k];\n};\n\n```\n```GO []\nfunc kInversePairs(n int, k int) int {\n MOD := 1000000007\n dp := make([]int, k+1)\n dp[0] = 1\n for i := 2; i <= n; i++ {\n for j := 1; j <= k; j++ {\n dp[j] = (dp[j] + dp[j-1]) % MOD\n }\n for j := k; j >= i; j-- {\n dp[j] = (dp[j] - dp[j-i] + MOD) % MOD\n }\n }\n return dp[k]\n}\n\n```\n```Rust []\nimpl Solution {\n pub fn k_inverse_pairs(n: i32, k: i32) -> i32 {\n let MOD = 1000000007;\n let mut dp = vec![0; (k + 1) as usize];\n dp[0] = 1;\n for i in 2..=n {\n for j in 1..=k {\n dp[j as usize] = (dp[j as usize] + dp[(j - 1) as usize]) % MOD;\n }\n for j in (i..=k).rev() {\n dp[j as usize] = (dp[j as usize] - dp[(j - i) as usize] + MOD) % MOD;\n }\n }\n dp[k as usize]\n }\n}\n\n```\n**Po resheniyu Java dostigayet 100%, naschet ostal\'nykh kodov ne znayu..**\n**upvote pozhaluysta!!\uD83D\uDE0A**\n\n\n
18
0
['C', 'Python', 'C++', 'Java', 'Go', 'Python3', 'Rust', 'JavaScript', 'C#']
5
k-inverse-pairs-array
Evolve from brute force to dp
evolve-from-brute-force-to-dp-by-yu6-ze2p
It is natrual to think of generating all permutations and count the inverse pairs for each permuation. I summarize some solutoins of 46. Permutations. If you ar
yu6
NORMAL
2020-06-09T07:09:14.538586+00:00
2020-06-09T20:38:51.114135+00:00
1,135
false
It is natrual to think of generating all permutations and count the inverse pairs for each permuation. I summarize some solutoins of [46. Permutations](https://leetcode.com/problems/permutations/discuss/676775/a-review-of-the-solutions). If you are familiar with anyone, you can at least have a brute force solution. If you are familiar with all, then you can pick one which is easy to compute inverse pairs.\n1. brute force, generate all permutations. I choose the approach that adds n to the permutations of 1 to n-1 because it is easy to compute inverse pairs.\n1.1 O(n^2 n!), generate all permutation and count inverse pairs for each one.\n```\npublic int kInversePairs(int n, int k) {\n return dfs(1,n,k,new ArrayList<>());\n }\n private int dfs(int num, int n, int k, List<Integer> lst) {\n if(num==n+1) return isKinv(k, lst);\n int count = 0;\n for(int i=0;i<=lst.size();i++) { \n List<Integer> perm = new ArrayList<>(lst);\n perm.add(i,num);\n count+=dfs(num+1,n,k,perm);\n }\n return count;\n }\n private int isKinv(int k, List<Integer> lst) {\n int s = lst.size();\n for(int i=0;i<s;i++) for(int j=i+1;j<s;j++) if(lst.get(i)>lst.get(j)) k--;\n return k==0 ? 1 : 0;\n }\n```\n1.2 Better brute force O(n!) When adding n to the permutation of 1 to n-1, the numbers on the right of n are all newly created inverse pairs with n. So we can compute the inverse pairs when generating the permutations. We no longer need the actual permutation becasue we can compute inverse pair without it.\n```\npublic int kInversePairs(int n, int k) {\n return dfs(1,n,k);\n }\n private int dfs(int num, int n, int k) {\n if(num==n+1) return k==0?1:0;\n int count = 0;\n for(int i=Math.max(0,k-num+1);i<=k;i++) count+=dfs(num+1,n,i); //inserting num may create at most num-1 inversions, so the remaining inversions is from max(0, k-(num-1)) to k\n return count;\n }\n```\n2. Memoization O(k*n^2)\n```\npublic int kInversePairs(int n, int k) {\n Integer[][] mem = new Integer[n+1][k+1];\n return dfs(1,n,k,mem);\n }\n private int dfs(int num, int n, int k, Integer[][] mem) {\n if(num==n+1) return k==0?1:0;\n if(mem[num][k]!=null) return mem[num][k];\n int count=0;\n for(int i=Math.max(0,k-num+1);i<=k;i++) count= (count+dfs(num+1,n,i,mem))%1000000007;\n return mem[num][k]=count;\n }\n```\n3. Bottom up dp O(k*n^2), transform #2 to dp literally. \ndp[i][j] means number of ways to add i until n to the array with j new inversions.\ndp[i][j]=dp[i+1][j]+dp[i+1][j-1]+...+dp[i+1][max(0,j-i+1)]\n```\n public int kInversePairs(int n, int k) {\n int[][] dp = new int[n+2][k+1];\n dp[n+1][0]=1;\n for(int i=n;i>0;i--)\n for(int j=0;j<=k;j++)\n for(int m=Math.max(0,j-i+1);m<=j;m++)\n dp[i][j] = (dp[i][j]+dp[i+1][m])%1000000007;\n return dp[1][k]; \n }\n```\n4. top down dp O(k*n^2). Basically same as #3 but with a clearer description for dp[i][j]. \ndp[i][j] means the number of arrays containing 1 to i and j inversions.\ndp[i][j] = dp[i-1][j]+dp[i-1][j-1]+...+dp[i-1][max(0,j-i+1)]\n\n```\npublic int kInversePairs(int n, int k) {\n int[][] dp = new int[n+1][k+1];\n dp[0][0]=1;\n for(int i=1;i<=n;i++)\n for(int j=0;j<=k;j++)\n for(int m=Math.max(0,j-i+1);m<=j;m++)\n dp[i][j] = (dp[i][j]+dp[i-1][m])%1000000007;\n return dp[n][k]; \n }\n```\n5. dp O(nk), the idea is from [@dreamchase](https://leetcode.com/problems/k-inverse-pairs-array/discuss/104815/Java-DP-O(nk)-solution).\nWhen j-i+1<=0\ndp[i][j] = dp[i-1][j]+dp[i-1][j-1]+...+dp[i-1][0]\ndp[i][j-1]=dp[i-1][j-1]+dp[i-1][j-2]+...+dp[i-1][0]\nSo when j<i , dp[i][j]=dp[i-1][j]+dp[i][j-1]\nWhen j-i+1>0, \ndp[i][j] = dp[i-1][j]+dp[i-1][j-1]+...+dp[i-1][j-i+1]\ndp[i][j-1]=dp[i-1][j-1]+dp[i-1][j-2]+...+dp[i-1][j-i+1]+dp[i-1][j-i]\n=> dp[i][j]=dp[i-1][j]+dp[i][j-1]-dp[i-1][j-i]\n```\npublic int kInversePairs(int n, int k) {\n int[][] dp = new int[n+1][k+1];\n dp[0][0]=1;\n int mod = 1000000007;\n for(int i=1;i<=n;i++) {\n dp[i][0]=1;\n for(int j=1;j<=k;j++) {\n dp[i][j] = (dp[i][j-1]+dp[i-1][j])%mod;\n if(j>=i) {\n dp[i][j]-=dp[i-1][j-i];\n dp[i][j]=(dp[i][j]+mod)%mod;\n } \n } \n }\n return dp[n][k]; \n }\n```
15
1
[]
1
k-inverse-pairs-array
[Python 376ms] A less confusing cumulative sum approach
python-376ms-a-less-confusing-cumulative-hhpw
This solution uses dynamic programming like the given solution but with a dummy dp[0][0] = 1 value for a more readable cumulative sum solution.\n\n\nclass Solut
chpchpchp
NORMAL
2019-04-27T16:16:18.766974+00:00
2019-04-27T16:16:18.767038+00:00
1,389
false
This solution uses dynamic programming like the given solution but with a dummy `dp[0][0] = 1` value for a more readable cumulative sum solution.\n\n```\nclass Solution(object):\n def kInversePairs(self, n, k):\n """\n :type n: int\n :type k: int\n :rtype: int\n """\n dp = [[0] * (k+1) for _ in range(n+1)]\n dp[0][0] = 1\n \n for i in range(1, n+1):\n cumsum = 0\n for j in range(k+1):\n if j == 0:\n dp[i][j] = 1\n cumsum += 1\n else:\n cumsum += dp[i-1][j]\n if j-i >= 0: # basically sliding window\n cumsum -= dp[i-1][j-i]\n dp[i][j] = cumsum % 1000000007\n \n return dp[n][k]\n```
14
2
['Python3']
4
k-inverse-pairs-array
Simple 3 Line O(nk) Python3 Solution with Intuitive Explanation 💯💯💯
simple-3-line-onk-python3-solution-with-66ir4
Intuition\n Describe your first thoughts on how to solve this problem. \nWe solve this problem using DP on n and k, with a clever combinatorial recursion:\n\nBa
jacoooooby
NORMAL
2024-01-27T04:15:29.417026+00:00
2024-01-27T04:25:39.763550+00:00
879
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe solve this problem using DP on $$n$$ and $$k$$, with a clever combinatorial recursion:\n\nBase Cases: \n\n- Whenever $$k=0$$ then there is exactly one way to arrange the array (i.e. in increasing order).\n`if k == 0: return 1`\n- Otherwise, whenever $$n=1$$ or $$k<0$$, we return $$0$$ since there\'s no way to get nonzero inverse pairs with one number and negative $$k$$ doesn\'t make sense.\n`if n == 1 or k < 0: return 0`\n\nRecursion: `return dp(n, k-1) + dp(n-1, k) - dp(n-1, k-n)`\n\n- Almost all permutations of $$1,...,n$$ with $$k-1$$ pairs can be transformed to have $$k$$ pairs by swapping the $$n$$ to move it to the front of the array - since $$n$$ is greater than all elements, it increases the number of inverse pairs by one. Hence the first term.\n- However, this doesn\'t lead to any permutations which have $$n$$ at the end of the array. But to count these, we simply need the number of permutations of $$1,...,n-1$$ with $$k$$ pairs, which is a subproblem. Hence the second term.\n- We also \'overcount\' for the initial permutations that start with $$n$$ at the front of the array (since you can\'t move it further forward). Since $$n$$ is greater than all other elements, in these cases it contributes to $$n-1$$ of the pairs. Thus it\'s equivalent to solve how to arrange the remaining $$n-1$$ numbers with $$(k-1)-(n-1) = k-n$$ pairs, which is also a subproblem. Hence the third term.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nWe implement the DP using a recursive function and cached memoization. The base cases should handle all recursive calls with negative $$k$$. Memory-wise, the method could be made more efficient (O(k)) by only memoizing subproblems with $$n$$ and $$n-1$$, perhaps using temporary lists, but I chose this way because it\'s much cleaner and faster to write.\n\n# Complexity\n- Time complexity: $$O(n*k)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n*k)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def kInversePairs(self, n: int, k: int) -> int:\n @cache\n def dp(n, k):\n if k == 0: return 1\n if n == 1 or k < 0: return 0\n return dp(n, k-1) + dp(n-1, k) - dp(n-1, k-n)\n return dp(n, k) % (10**9+7)\n \n```
12
0
['Dynamic Programming', 'Recursion', 'Combinatorics', 'Python3']
4
k-inverse-pairs-array
✅ O(N*K) DP Solution || C++
onk-dp-solution-c-by-sambit_2022-klgy
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
sambit_2022
NORMAL
2024-01-27T00:20:13.659480+00:00
2024-01-27T00:20:13.659512+00:00
2,970
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n**O(N*K)**\n\n- Space complexity:\n**O(N*K)**\n\n# Code\n```\nclass Solution {\npublic:\n int mod =1000000007;\n\n\n int kInversePairs(int n, int k) {\n\n int dp[1001][1002] = {0};\n\n dp[0][0] =1;\n\n for(int i=1;i<=n;i++)\n {\n long int val=0;\n \n for(int j=0;j<=k;j++)\n {\n val+=dp[i-1][j];\n if(j>=i)\n {\n val-=dp[i-1][j-i];\n }\n dp[i][j]=val%mod;\n }\n }\n return dp[n][k];\n \n }\n};\n```
10
0
['Dynamic Programming', 'C++']
3
k-inverse-pairs-array
[C++] Recursion + Memoization O(N*K) (Bruteforce To Optimised)
c-recursion-memoization-onk-bruteforce-t-hkds
\nclass Solution {\npublic:\n //Bruteforce = All permutations of nums, count inverse pairs, build result. O(N!) => TLE\n /*\n f(n, k) = f(n-1, k) + f(n
shady41
NORMAL
2022-07-17T08:16:16.419817+00:00
2022-07-20T09:13:57.258047+00:00
1,700
false
```\nclass Solution {\npublic:\n //Bruteforce = All permutations of nums, count inverse pairs, build result. O(N!) => TLE\n /*\n f(n, k) = f(n-1, k) + f(n-1, k-1) + ... + f(n-1, k-n-1);\n Picked i, inversions due to this = nos. smaller than i, to be placed after it.\n\tfor eg. 1, 2, 3, 4\n\tif 3 is placed first, 1 and 2 cause inversion with 3. \n\tthus inversions = num - 1\n\twe can build result with smaller n since relative order is maintained after n-1, {1, 2, 3, 4}, 3 is placed, {1, 2, 4} <=> {1, 2, 3}\n\n T.C = O(n*n*k), TLE since 10^3^3 == 10^9\n */\n /*\n int dp[1001][1001];\n int mod = 1e9+7;\n int f(int n, int k){\n if(k<=0) return !k;\n if(dp[n][k]!=-1) return dp[n][k];\n int res = 0;\n \n for(int i = 1; i<=n; i++){\n res = (res + f(n-1, k-i-1))%mod;\n }\n \n return dp[n][k] = res;\n }\n int kInversePairs(int n, int k) {\n memset(dp, -1, sizeof(dp));\n return f(n,k);\n }\n */\n /*\n\tf(n, k) = f(n-1, k) + f(n-1, k-1) + f(n-1, k-2) + ... + f(n-1, k-n+1) --->(1)\n\tf(n, k-1) = f(n-1, k-1) + f(n-1, k-2) + f(n-1, k-3) + ... + f(n-1, k-n+1)+ f(n-1, k-n) --->(2)\n\n\tf(n-1, k-n) is additional term, so we substract it\n \n Using (2) in (1)\n \n f(n, k) = f(n-1, k) + f(n, k-1) - f(n-1, k-n)\n \n T.C = O(n*k) S.C = (n*k + min(n, k))\n */\n int dp[1001][1001];\n int mod = 1e9+7;\n long f(int n, int k){\n if(k<=0) return !k;\n if(n<=0) return 0;\n if(dp[n][k]!=-1) return dp[n][k];\n \n dp[n][k] = (f(n-1, k) + f(n, k-1))%mod;\n return dp[n][k] = (dp[n][k] - f(n-1, k-n) + mod)%mod;\n }\n int kInversePairs(int n, int k) {\n memset(dp, -1, sizeof(dp));\n return f(n,k);\n }\n};\n```
9
0
['Dynamic Programming', 'Memoization', 'C', 'C++']
2
k-inverse-pairs-array
Short & Simple | Easy | Clean C++ | Grid DP | O(N*K) | just 2 Loops ^_^
short-simple-easy-clean-c-grid-dp-onk-ju-ewb0
\nclass Solution {\npublic:\n int kInversePairs(int n, int k) {\n long long int dp[n+1][k+1];\n int mod = 1000000007;\n for(int i = 0 ;i
viv_shubham
NORMAL
2021-06-19T18:17:01.310469+00:00
2021-06-19T18:21:12.639286+00:00
612
false
```\nclass Solution {\npublic:\n int kInversePairs(int n, int k) {\n long long int dp[n+1][k+1];\n int mod = 1000000007;\n for(int i = 0 ;i<=k;i++)dp[0][i] = 0;\n for(int i = 0 ;i<=n;i++)dp[i][0] = 1;\n for(int i = 1;i<=n;i++){\n for(int j = 1;j<=k;j++){\n long long int val = (j-i>=0) ? dp[i-1][j-i] : 0;\n dp[i][j] = (dp[i][j-1] + dp[i-1][j] + (mod-val))%mod;\n }\n }\n return dp[n][k]%mod;\n }\n};\n```
9
2
[]
2
k-inverse-pairs-array
Solution with DP - DP Iterative Optimization - O(N*K)
solution-with-dp-dp-iterative-optimizati-de76
Intuition\nif I have an array with size n and k inverse pairs, what will happend if I add an extra element (n + 1) which is greater than all of n elements?\n\n#
Kareem_Elgoker
NORMAL
2024-01-27T16:31:33.702831+00:00
2024-01-27T16:31:33.702859+00:00
312
false
# Intuition\nif I have an array with size n and k inverse pairs, what will happend if I add an extra element (n + 1) which is greater than all of n elements?\n\n# Approach\nIf I add the (n + 1) at the end (position n+1) -> then the number of inverse pairs will remains the same \n\nIf I add the (n + 1) at (position n) -> then the number of inverse pairs will increase by one\n\nIf I add the (n + 1) at (position n-1) -> then the number of inverse pairs will increase by two\n\n.\n.\n.\n.\n\nIf I add the (n + 1) at (position 0) -> then the number of inverse pairs will increase by n\n\n\nSo :\nlet dp[i][j] represent the number of arrays with i elements and j inverse pairs\n\nThis value dp[i][j] should be added to dp[i+1][k]\nwhere k is from j to j + i (Push DP)\n\nWhy? Because extra element of n has the same value of the previous n but with extra range of inverse pairse from 0 to n.\n\n\nFinally we can\'t add this value by a for loop -> TLE\nSo we can make a partial sum optimization on the dp -> Look at the code\n# Complexity\n- Time complexity:\nO(N * K)\n\n- Space complexity:\nO(N * K)\n\n# Code\n```\nclass Solution {\npublic:\n #define mod 1000000007\n int kInversePairs(int n, int k) {\n vector<vector<long long>> dp(n + 1, vector<long long>(k + 2));\n dp[1][0] = 1;\n\n for (int i = 1; i < n; ++i) {\n for (int j = 0; j <= k; ++j) {\n dp[i + 1][j] += dp[i][j];\n dp[i + 1][min(j + i + 1, k + 1)] -= dp[i][j];\n }\n for(int j = 1; j <= k; ++j)\n {\n dp[i + 1][j] += dp[i + 1][j - 1];\n dp[i + 1][j] += mod;\n dp[i + 1][j] %= mod;\n }\n }\n\n return dp[n][k];\n }\n};\n```
8
0
['C++']
1
k-inverse-pairs-array
java,DP.Thank you so much @GardenAAA for your advice.
javadpthank-you-so-much-gardenaaa-for-yo-3hbg
\nthink in DP.\n(n+1,k) means the sum of arrays that consist of n+1 number with k inverse pairs.\nfor arrays that match (n,k),we put the (N+1)th number at the e
iamfrog
NORMAL
2017-06-25T03:21:41.385000+00:00
2017-06-25T03:21:41.385000+00:00
2,693
false
\nthink in DP.\n(n+1,k) means the sum of arrays that consist of n+1 number with k inverse pairs.\nfor arrays that match (n,k),we put the (N+1)th number at the end ,so the new array match (n+1,k).\nfor arrays that match (n,k-1),we put the (N+1)th number before the last number, the sum of inverse pairs increase 1,so the new array match (n+1,k).\n...\n the max increase is n (put the (N+1)th number at the begin)\n\nThus (n+1,k) equals (n,k)+(n,k-1)+(n,k-2)+.....+\uff08n,k-n\uff09\nbelow is my code:\n```java\npublic int kInversePairs(int n, int k) {\n long[][] dp = new long[n][k+1];\n dp[0][0]=1;//mean sum of arrays that consist of 1 with 0 inverse pairs\n for(int i=1;i<n;i++){\n for(int j=0;j<=k;j++){\n for(int m=j;m>=0&&m>=(j-i);m--){\n dp[i][j]+=dp[i-1][m];\n }\n dp[i][j]=dp[i][j]%1000000007;\n }\n }\n return (int)dp[n-1][k];\n }\n```\nThank you so much @GardenAAA for your advice.\nthe above code can be optimizated,\n```java\npublic int kInversePairs(int n, int k) {\n long[][] dp = new long[n][k+1];\n dp[0][0]=1;\n for(int i=1;i<n;i++){\n for(int j=0;j<=k;j++){\n if(j>0){\n dp[i][j]=dp[i][j-1]+dp[i-1][j];\n dp[i][j]=j-i>0?(dp[i][j]-dp[i-1][j-i-1]):dp[i][j];\n }\n else{\n for(int m=j;m>=0&&m>=(j-i);m--){\n dp[i][j]+=dp[i-1][m];\n }\n }\n dp[i][j]=dp[i][j]>0?dp[i][j]%1000000007:(dp[i][j]+1000000007)%1000000007;\n }\n }\n return (int)dp[n-1][k];\n }\n```\nHope you have better method.
8
3
[]
5
k-inverse-pairs-array
✅☑Beats 93.57% Users || Easy Understood Solution With space[k] and time[O(n * k)] || 2 Approaches🔥
beats-9357-users-easy-understood-solutio-y5co
\n\n# Explaination \n - Objective:\n - Calculate the count of permutations of length n with k inverse pairs.\n \n - Approach:\n - Utilizes dynamic prog
MindOfshridhar
NORMAL
2024-01-27T19:03:04.474573+00:00
2024-01-27T19:11:10.051702+00:00
483
false
![Screenshot 2024-01-25 12924.PNG](https://assets.leetcode.com/users/images/ffdc4c8f-fe12-433d-9b5a-ee93aead459c_1706382129.8069391.png)\n\n# Explaination \n - **Objective**:\n - Calculate the count of permutations of length n with k inverse pairs.\n \n - **Approach**:\n - Utilizes dynamic programming with a 2D array dp[i][j] representing permutations of length i with j inverse pairs.\n - **Initialization**:\n - dp[0][0] = 1 for an empty permutation with 0 inverse pairs.\n - **Dynamic Programming**:\n - Updates dp[i][j] using the recurrence relation:\n - dp[i][j] = dp[i][j - 1] + dp[i - 1][j] (accumulating permutations, excluding the current element).\n - Subtract dp[i - 1][j - i] if j >= i.\n - **Modulo Operation**:\n - Applies modulo (10**9 + 7) to each update for numerical stability.\n - **Final Result**:\n - Returns dp[n][k] modulo (10**9 + 7).\n\n# Complexity\n- Time complexity: O(n * k)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(k)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n# code 1\n```\nclass Solution:\n def kInversePairs(self, n: int, k: int) -> int:\n # Initialize a 2D array to store the results\n dp = [[0] * (k + 1) for _ in range(n + 1)]\n\n # Base case: when n is 0, there\'s only one permutation with 0 inverse pairs\n dp[0][0] = 1\n\n # Fill in the DP table\n for i in range(1, n + 1):\n dp[i][0] = 1 # Number of permutations with 0 inverse pairs is always 1\n for j in range(1, k + 1):\n dp[i][j] = (dp[i][j - 1] + dp[i - 1][j]) % (10**9 + 7)\n if j >= i:\n dp[i][j] = (dp[i][j] % (10**9 + 7) - dp[i - 1][j - i] ) % (10**9 + 7)\n\n return dp[n][k] % (10**9 + 7)\n```\n# code 2\n```\nclass Solution:\n def kInversePairs(self, n: int, k: int) -> int:\n # Initialize the dynamic programming array dp with 1 at index 0 and 0 elsewhere\n dp, mod = [1] + [0] * k, 1000000007\n\n # Iterate through each element in the range [0, n)\n for i in range(n):\n tmp, sm = [], 0 # Initialize temporary arrays\n for j in range(k + 1):\n sm += dp[j] # Accumulate values from the previous dp array\n if j - i >= 1:\n sm -= dp[j - i - 1] # Subtract values that are no longer relevant\n sm %= mod # Apply modulo to prevent overflow\n tmp.append(sm) # Store the accumulated value in the temporary array\n dp = tmp # Update dp array with the temporary array\n\n return dp[k] # The final result is the count of permutations with k inverse pairs\n\n```\n![leetcode up1.png](https://assets.leetcode.com/users/images/894d977c-3583-4b5c-9489-abad0d7e9893_1706382167.631566.jpeg)\n
7
0
['Hash Table', 'Math', 'Dynamic Programming', 'Backtracking', 'Depth-First Search', 'Recursion', 'Memoization', 'Python', 'Python3', 'Python ML']
2
k-inverse-pairs-array
[C++] Simple iterative dp O(nk)
c-simple-iterative-dp-onk-by-facelessvoi-4ggc
The problem reduces to distributing k inversions among n positions. That is every element can take part in only certain number of inversions. So for nth positio
facelessvoid
NORMAL
2018-02-24T11:24:22.458178+00:00
2018-02-24T11:24:22.458178+00:00
743
false
The problem reduces to distributing k inversions among n positions. That is every element can take part in only certain number of inversions. So for nth position, it can have 0,1,2,...,n-1 inversions. This can be written as DP using the formula ```dp[n][k] = dp[n-1][0] + dp[n-1][1] + ... + dp[n-1][k]``` corresponding to nth element participating in k inversions, k-1 inversions, k-2 inversions... till nth element participating in 0 inversions. This can be maintained as running ```sum```. Also, one thing to handle would be if ```k >= n``` (in the iterative form), this is because if we want 3rd position to have 3 inversions, that is not possible since there are just 2 elements in front of the 3rd element. So we would have to subtract ```dp[n-1][k-n]``` from the running sum. ``` #define N 1010 int dp[N][N]; const int MOD = 1e9+7; class Solution { public: int kInversePairs(int n, int k) { for(int i=0;i<=n;i++) dp[i][0] = 1; for(int i=1;i<=n;i++){ int sum = dp[i-1][0]; for(int j=1;j<=k;j++){ if(j>=i) sum -= dp[i-1][j-i]; if(sum < 0) sum += MOD; (sum += dp[i-1][j])%=MOD; dp[i][j] = sum; } } return dp[n][k]; } }; ```
7
0
[]
1
k-inverse-pairs-array
JAVA || Simple and Easy Solution|| 97% faster code
java-simple-and-easy-solution-97-faster-32n6v
\nclass Solution {\n public int kInversePairs(int n, int k) {\n int MOD = 1000000007;\n int[][] opt = new int[k + 1][n];\n for (int i =
shivrastogi
NORMAL
2022-07-17T02:47:03.694737+00:00
2022-07-17T02:47:03.694768+00:00
1,276
false
```\nclass Solution {\n public int kInversePairs(int n, int k) {\n int MOD = 1000000007;\n int[][] opt = new int[k + 1][n];\n for (int i = 0; i <= k; i++) {\n for (int j = 0; j < n; j++) {\n if (i == 0) {\n opt[i][j] = 1;\n } else if (j > 0) {\n opt[i][j] = (opt[i - 1][j] + opt[i][j - 1]) % MOD;\n if (i >= j + 1) {\n opt[i][j] = (opt[i][j] - opt[i - j - 1][j - 1] + MOD) % MOD;\n }\n }\n }\n }\n\n return opt[k][n - 1];\n }\n}\n```
6
1
['Dynamic Programming', 'Java']
1
k-inverse-pairs-array
O(n^2) DP using SINGLE ARRAY of size k
on2-dp-using-single-array-of-size-k-by-t-t3o4
Upvote if you thought this code was helpful!\n\nJoin our discord to meet other people preparing for interviews!\nhttps://discord.gg/Aj2uT5rP\n\nC++\nc++\nclass
TLDRAlgos
NORMAL
2022-07-17T01:11:50.868507+00:00
2022-07-17T01:13:19.366411+00:00
695
false
**Upvote** if you thought this code was helpful!\n\n**Join our discord** to meet other people preparing for interviews!\n**https://discord.gg/Aj2uT5rP**\n\n**C++**\n```c++\nclass Solution {\npublic:\n int kInversePairs(int n, int k) {\n const int MOD = 1e9 + 7;\n vector<int> dp(k + 1);\n dp[0] = 1;\n for (int num = 0; num < n; num++) {\n int mx = n - num - 1;\n int window = 0;\n for (int i = 0; i <= mx; i++) {\n if (k - i < 0) break;\n window += dp[k - i];\n if (window >= MOD) window -= MOD;\n }\n for (int i = k; i >= 0; i--) {\n int curr = dp[i];\n dp[i] = window;\n window -= curr;\n if (window < 0) window += MOD;\n if (i - mx - 1 >= 0) {\n window += dp[i - mx - 1];\n if (window >= MOD) window -= MOD;\n }\n }\n \n }\n return dp[k];\n }\n};\n```\n\n**Python3**\n```python\nclass Solution:\n def kInversePairs(self, n: int, k: int) -> int:\n MOD = 10 ** 9 + 7\n dp = [1] + [0] * k\n for num in range(n):\n mx = n - num - 1\n window = 0\n for i in range(mx + 1):\n if k - i < 0:\n break\n window += dp[k - i]\n for i in range(k, -1, -1):\n curr = dp[i]\n dp[i] = window\n window -= curr\n if window < 0:\n window += MOD\n if i - mx - 1 >= 0:\n window += dp[i - mx - 1]\n return dp[k] % MOD\n```\n\n**Time Complexity**: O(n^2)\n**Space Complexity**: O(k)
6
0
['Dynamic Programming']
0