python |
Pythonタグが付けられた新着投稿 - Qiita |
【AHC020 参加記】初参加の初心者でもそれなりに善戦できるぞという話 |
https://qiita.com/halcyonFX/items/c6d7ebdf375f359c596c
|
halcyon |
2023-06-11 20:36:51 |
python |
Pythonタグが付けられた新着投稿 - Qiita |
PythonとPEP8: lambda式の適切な使用について |
https://qiita.com/yukisakakima/items/449b47c79f743887bb9f
|
peplambda |
2023-06-11 20:03:15 |
js |
JavaScriptタグが付けられた新着投稿 - Qiita |
Auth.jsを完全に理解する (基本編) #1 |
https://qiita.com/kage1020/items/fca49e9b42b972b70b8c
|
authjs |
2023-06-11 20:39:27 |
Ruby |
Railsタグが付けられた新着投稿 - Qiita |
【Rails】ブラウザを閉じてもログインセッションを維持させる |
https://qiita.com/sakuchi/items/cdc26a67b43feee0882a
|
activerecord |
2023-06-11 20:45:55 |
Ruby |
Railsタグが付けられた新着投稿 - Qiita |
新規アプリケーションを立ち上げよう |
https://qiita.com/sa109/items/fe210dcbda8df382ef2b
|
cdpictweet |
2023-06-11 20:28:30 |
海外TECH |
MakeUseOf |
How to Use Your MacBook With the Lid Closed in Clamshell Mode |
https://www.makeuseof.com/use-macbook-with-lid-closed/
|
clamshell |
2023-06-11 11:15:19 |
海外TECH |
DEV Community |
Explain Dynamic Programming and Other Techniques with Examples |
https://dev.to/aradwan20/explain-dynamic-programming-and-other-techniques-with-examples-505p
|
Explain Dynamic Programming and Other Techniques with Examples Introduction Longest Increasing Subsequence Problem Description Solution in JavaScript Longest Common Subsequence Problem Description Solution in JavaScript Longest Palindromic Substring Problem Description Solution in JavaScript Longest Palindromic Subsequence Problem Description Solution in JavaScript Maximum Product Subarray Problem Description Solution in JavaScript Largest Rectangle in a Histogram Problem Description Solution in JavaScript Egg Dropping Problem Problem Description Solution in JavaScript Counting Bits Problem Description Solution in JavaScript Perfect Squares Problem Description Solution in JavaScript Unique PathsProblem DescriptionSolution in JavaScriptConclusion IntroductionIn this article we will dive into the world of dynamic programming focusing on solving some programming challenges using also some other techniques We will break down each problem present different solutions in JavaScript and provide a clear concise explanation Longest Increasing Subsequence Problem DescriptionThe Longest Increasing Subsequence LIS problem is a classic programming challenge that requires finding the length of the longest subsequence of a given sequence such that all elements of the subsequence are sorted in increasing order A subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements For example consider the sequence The longest increasing subsequence here is and its length is Solution in JavaScriptTo solve the LIS problem in JavaScript we can use dynamic programming to break down the problem into smaller subproblems and solve them efficiently Here s a step by step solution with detailed comments to help you understand the code function longestIncreasingSubsequence nums const n nums length if n return Initialize an array of length n filled with s as the minimum length of any LIS is const dp Array n fill Iterate through the elements in the nums array for let i i lt n i for let j j lt i j Check if the current element is greater than the previous one if nums i gt nums j If it is update the dp array with the maximum length found so far dp i Math max dp i dp j Find the maximum length of the LIS by iterating through the dp array let maxLIS dp for let i i lt n i maxLIS Math max maxLIS dp i Return the maximum length of the LIS return maxLIS To understand this solution let s break down the key parts We initialize an array called dp with the same length as the input array nums and fill it with s This array will store the length of the LIS ending at each index We then use two nested loops to iterate through the elements in the nums array If the current element is greater than the previous one we update the dp array with the maximum length found so far Finally we find the maximum length of the LIS by iterating through the dp array and return it Time complexity and space complexity are as follows Time Complexity O n The time complexity of the solution is O n because we have two nested loops The outer loop iterates over the elements in the input array nums and the inner loop iterates over the elements up to the current index in the outer loop In the worst case both loops will run n times resulting in a total of n n operations Therefore the time complexity is O n Space Complexity O n The space complexity of the solution is O n because we are using an additional array dp to store the length of the LIS ending at each index The size of the dp array is equal to the length of the input array nums which is n Apart from the dp array we use a few variables but their space consumption is constant and does not depend on the input size Therefore the space complexity is O n If you ask is there a better and more efficient solution for the same challenge Yes there is a better time complexity solution to the Longest Increasing Subsequence problem using a binary search algorithm The time complexity for this approach is O n log n Here is the code and explanation for the better approach function longest increasing subsequence nums let tails tails nums let length for let i i lt nums length i if nums i lt tails tails nums i else if nums i gt tails length tails length nums i else tails lower bound tails length nums i nums i return length function lower bound arr start end key while start lt end let mid Math floor start end if arr mid lt key start mid else end mid return start In this approach we maintain an array tails which stores the minimum tail elements of all increasing subsequences we have seen so far The tails array is sorted and its length represents the length of the longest increasing subsequence We iterate through the input array nums and for each element If the element is smaller than the first element in tails we replace the first element with the current element If the element is greater than the last element in tails we append the element to the end of tails increasing the length of the LIS by Otherwise we find the smallest element in tails that is greater than or equal to the current element using the lower bound function binary search and replace that element with the current element This approach is faster because for each element in the input array we perform a binary search operation that takes O log n time Since there are n elements in the input array the overall time complexity is O n log n The primary difference between the O n and O nlog n solutions is the technique used to update the subproblem solutions The O n approach uses dynamic programming with a nested loop whereas the O nlog n approach uses binary search to optimize the updates The O n log n solution is more efficient especially for large input arrays Longest Common Subsequence Problem DescriptionThe Longest Common Subsequence LCS problem is a classic computer science problem that involves finding the longest subsequence common to two given sequences A subsequence is a sequence that appears in the same order in both sequences but not necessarily consecutively For example the longest common subsequence of the strings ABCD and ACDF is ACD Solution in JavaScriptTo solve the Longest Common Subsequence problem we will use dynamic programming This approach allows us to break the problem down into smaller subproblems and solve them only once Here s the JavaScript solution function longestCommonSubsequence str str const m str length const n str length const dp Array from length m gt Array n fill for let i i lt m i for let j j lt n j if str i str j dp i j dp i j else dp i j Math max dp i j dp i j return dp m n To understand the code let s break it down step by step We first define the lengths of both input strings m and n We create a D array dp with dimensions m x n and initialize all elements to We loop through each character of both strings comparing them at each step If the characters match we increment the value in the dp array at the current position by adding to the value at the diagonal position up and left This represents adding the current matched character to the LCS found so far If the characters don t match we take the maximum value from either the cell above or the cell to the left This represents considering the LCS found so far without the current characters After looping through both strings the value in the bottom right corner of the dp array represents the length of the Longest Common Subsequence The time complexity of this solution is O m n where m and n are the lengths of the input strings This is because we need to loop through each character in both strings and compare them The space complexity of the solution is also O m n due to the D array dp that we create to store the intermediate results of the subproblems Let s have some optimization and do a code review The dynamic programming solution provided above has a time complexity of O m n where m and n are the lengths of the input strings While it may not be possible to significantly improve the time complexity for the general case we can optimize the space complexity of the solution The current space complexity is also O m n due to the D array dp We can optimize this by using a rolling array and only keeping track of the current and previous rows This reduces the space complexity to O min m n Here s the optimized JavaScript solution function longestCommonSubsequence str str if str length lt str length str str str str const m str length const n str length const dp Array from length gt Array n fill for let i i lt m i for let j j lt n j if str i str j dp i j dp i j else dp i j Math max dp i j dp i j return dp m n In this optimized solution we first swap str and str if str has a shorter length than str This ensures that str is always the shorter string which reduces space complexity Then instead of initializing a D array with dimensions m x n we create a D array with dimensions x n Inside the loops we update the dp array using the modulo operator to alternate between the two rows This means that we only store the current row and the previous row effectively reducing the space complexity to O min m n Please note that the time complexity remains O m n because we still need to loop through each character in both strings and compare them However the space complexity is now optimized making the solution more efficient in terms of memory usage Longest Palindromic Substring Problem DescriptionThe Longest Palindromic Substring problem involves finding the longest contiguous substring of a given string that reads the same forward and backward For example given the string babad the longest palindromic substring is either bab or aba Solution in JavaScriptOne way to solve this problem is by using dynamic programming Here s the JavaScript solution function longestPalindromicSubstring s const n s length const dp Array from length n gt Array n fill false let maxLen let start for let i i lt n i dp i i true for let len len lt n len for let i i lt n len i const j i len if len dp i j s i s j else dp i j s i s j amp amp dp i j if dp i j amp amp len gt maxLen maxLen len start i return s substring start start maxLen In this solution we first create a D array dp where dp i j is true if the substring from index i to j is a palindrome We initialize the diagonal elements of dp as true since single characters are always palindromes Next we loop through the string using two nested loops The outer loop iterates through the possible lengths of substrings from to the length of the input string and the inner loop iterates through the starting positions of the substrings If the current substring is a palindrome we update the dp array and track the start position and maximum length of the palindrome Finally we return the longest palindromic substring using the substring method Time complexity O n where n is the length of the input string This is because we need to loop through all possible substrings and check if they are palindromes Space complexity O n due to the D array dp that stores the palindrome information for all possible substrings Dynamic programming is just one of the approaches to solve the Longest Palindromic Substring problem and I provided it because it s a widely used technique for such problems However there are other approaches to solve this problem and I can provide an alternative solution using an expand around center technique The expand around center technique is based on the idea of iterating through the string and for each character expanding outwards to find the longest palindromic substring that includes that character Here s the solution in JavaScript using this approach function expandAroundCenter s left right while left gt amp amp right lt s length amp amp s left s right left right return right left function longestPalindromicSubstring s if s null s length lt return let start let end for let i i lt s length i const len expandAroundCenter s i i const len expandAroundCenter s i i const len Math max len len if len gt end start start i Math floor len end i Math floor len return s substring start end In this solution we first define a helper function expandAroundCenter which returns the length of the longest palindromic substring centered around the given indices Then we iterate through the input string and call the helper function to find the longest palindromic substring for each character Time complexity O n where n is the length of the input string In the worst case we need to expand around each character in the input string which takes quadratic time Space complexity O as we are not using any additional data structures to store intermediate results and the memory usage does not depend on the size of the input string This approach may have better performance than dynamic programming for some cases because it can skip some unnecessary checks when expanding around the center However both methods still have a time complexity of O n So is there a better time complexity then O n Yes there is an algorithm called Manacher s Algorithm that solves the Longest Palindromic Substring problem with a better time complexity of O n This algorithm is specifically designed to find the longest palindromic substring more efficiently by avoiding redundant checks and utilizing previously calculated information Here s the implementation of Manacher s Algorithm in JavaScript function manachersAlgorithm s if s null s length return let modifiedString for let i i lt s length i modifiedString s i const p new Array modifiedString length fill let center let rightBoundary let maxLen let maxLenCenter for let i i lt modifiedString length i if rightBoundary gt i const mirror center i p i Math min rightBoundary i p mirror while i p i lt modifiedString length amp amp i p i gt amp amp modifiedString i p i modifiedString i p i p i if i p i gt rightBoundary center i rightBoundary i p i if p i gt maxLen maxLen p i maxLenCenter i const start Math floor maxLenCenter maxLen return s substring start start maxLen In this algorithm we first modify the input string by adding special characters e g between the original characters This helps to handle even and odd length palindromes uniformly Then we use an array p to store the palindrome radius centered at each character of the modified string We iterate through the modified string and update the palindrome radius for each character while keeping track of the right boundary of the current palindrome and its center We utilize the information about the previously calculated palindrome radius to skip some redundant checks and avoid extra work Time complexity O n where n is the length of the input string Manacher s Algorithm performs a linear number of operations by avoiding redundant checks and utilizing previously calculated information Space complexity O n as we store the palindrome radius for each character of the modified string which has a length proportional to the input string length Manacher s Algorithm provides a faster solution to the Longest Palindromic Substring problem compared to the dynamic programming and expand around center methods which have a time complexity of O n Longest Palindromic Subsequence Problem DescriptionIn this problem we need to find the longest palindromic subsequence in a given string Unlike the substring a subsequence doesn t require the characters to be contiguous in the original string but they must maintain their order Solution in JavaScriptWe can solve this problem using dynamic programming The idea is to create a D table to store the lengths of the longest palindromic subsequences of the substrings function longestPalindromicSubsequence s const n s length const dp Array from length n gt Array n fill for let i i lt n i dp i i for let len len lt n len for let i i lt n len i const j i len if s i s j dp i j dp i j else dp i j Math max dp i j dp i j return dp n In this solution we first initialize a D table dp of size n x n where n is the length of the input string We set the diagonal elements of dp to since a single character is always a palindrome We then iterate through the table filling it with the lengths of the longest palindromic subsequences for all substrings If the characters at the beginning and end of the substring are the same we add to the value of the inner substring Otherwise we set the value to the maximum of the previous row and previous column The final answer is stored in the top right cell of the table dp n Time complexity O n where n is the length of the input string We need to fill the D table of size n x n Space complexity O n as we store the lengths of the longest palindromic subsequences in the dp table Our usual question Is there a better time or space complexity than O n There isn t a significantly better time complexity than O n for the Longest Palindromic Subsequence problem using dynamic programming However you can optimize the space complexity using a rolling array or two D arrays instead of a D array Here s an optimized solution with a space complexity of O n function longestPalindromicSubsequence s const n s length let prev Array n fill let curr Array n fill for let i n i gt i curr i for let j i j lt n j if s i s j curr j prev j else curr j Math max prev j curr j prev curr curr prev return prev n In this solution we use two D arrays prev and curr to represent the previous row and current row of the D dp table This reduces the space complexity to O n while maintaining the same time complexity of O n In summary the time complexity remains O n but the space complexity is improved to O n using this optimized approach Maximum Product Subarray Problem DescriptionThe Maximum Product Subarray problem involves finding the contiguous subarray within a one dimensional array of numbers that has the largest product The input array may contain both positive and negative numbers Solution in JavaScript To solve this problem we can use dynamic programming We keep track of the maximum and minimum product subarrays ending at each position as the current number may be negative which can turn the minimum product into the maximum product when multiplied Here s the solution in JavaScript function maxProductSubarray nums const n nums length let maxProd nums let minProd nums let maxSoFar nums for let i i lt n i let temp maxProd maxProd Math max nums i Math max nums i maxProd nums i minProd minProd Math min nums i Math min nums i temp nums i minProd maxSoFar Math max maxSoFar maxProd return maxSoFar In this solution we iterate through the input array nums At each position we calculate the maximum and minimum product subarrays ending at that position We update the overall maximum product maxSoFar whenever we find a larger product The time complexity of this solution is O n since we only make one pass through the input array The space complexity is O as we only use constant extra space to store the intermediate results In summary this JavaScript solution has a time complexity of O n and space complexity of O for the Maximum Product Subarray problem Largest Rectangle in a Histogram Problem DescriptionThe Largest Rectangle in a Histogram problem involves finding the largest rectangular area that can be formed within a histogram A histogram is represented as an array of integers where each element represents the height of a bar and the width of each bar is Solution in JavaScriptTo solve this problem we can use a stack data structure to keep track of the indices of the bars in the histogram This method helps us efficiently find the largest rectangle possible for each bar Here s the solution in JavaScript function largestRectangleArea heights const stack let maxArea for let i i lt heights length i const h i heights length heights i while stack length gt amp amp h lt heights stack stack length const height heights stack pop const width stack length i i stack stack length maxArea Math max maxArea height width stack push i return maxArea In this solution we iterate through the input array heights We maintain a stack to keep track of the indices of the bars in non decreasing order of their heights When we find a bar with a smaller height we pop the elements from the stack and calculate the area of the rectangle that can be formed using the popped bar as the shortest one The time complexity of this solution is O n since we push and pop each element of the input array heights at most once The space complexity is O n as we use a stack to store the indices of the bars In summary this JavaScript solution has a time complexity of O n and space complexity of O n for the Largest Rectangle in a Histogram problem The solution provided above with a time complexity of O n and space complexity of O n is considered optimal for the Largest Rectangle in a Histogram problem It s unlikely that you would find a significantly more efficient algorithm in terms of time or space complexity The reason is that in the worst case you have to examine each bar in the histogram at least once to determine the largest rectangular area This fact necessitates a lower bound time complexity of O n The stack based solution above takes advantage of this by maintaining a stack of indices ensuring that each bar is only processed once Egg Dropping Problem Problem DescriptionThe Egg Dropping Problem is a classic problem in which you are given n eggs and a building with k floors You need to determine the highest floor from which an egg can be dropped without breaking The objective is to find the minimum number of attempts needed to find the solution Solution in JavaScriptThe Egg Dropping Problem can be solved using dynamic programming The idea is to use a D array dp where dp i j represents the minimum number of attempts required to find the highest floor from which an egg can be dropped without breaking given i eggs and j floors function eggDrop n k const dp Array n fill map gt Array k fill for let i i lt n i dp i dp i for let j j lt k j dp j j for let i i lt n i for let j j lt k j dp i j Infinity for let x x lt j x const res Math max dp i x dp i j x dp i j Math min dp i j res return dp n k The time complexity of this solution is O n k and the space complexity is O n k However it is possible to optimize this solution further by using binary search instead of a linear search for the inner loop This will reduce the time complexity to O n k log k Overall the Egg Dropping Problem is a challenging problem that can be solved using dynamic programming By breaking down the problem into smaller subproblems and solving each subproblem only once we can find the optimal solution and minimize the number of attempts needed to find the highest floor from which an egg can be dropped without breaking Counting Bits Problem DescriptionGiven a non negative integer num for every number i in the range ≤i ≤num calculate the number of s in their binary representation and return them as an array Solution in JavaScriptWe can solve this problem by using dynamic programming We can start by initializing an array of length num with all values set to zero Then for each index i from to num we can update the value at i to be equal to the value at i divided by plus the remainder of i divided by This works because the number of s in the binary representation of a number i is equal to the number of s in the binary representation of i plus if i is odd or if i is even Here is the JavaScript code for this solution function countBits num const dp new Array num fill for let i i lt num i dp i dp Math floor i i return dp The time complexity of this solution is O n where n is the input number num This is because we loop through all numbers from to num The space complexity is also O n because we use an array of length num to store the number of s for each number Overall this is a simple and efficient solution to the counting bits problem and it demonstrates the power of dynamic programming in solving algorithmic challenges Perfect Squares Problem DescriptionGiven a positive integer n find the least number of perfect square numbers for example which sum up to n Solution in JavaScriptTo solve this problem we can use dynamic programming We can create an array dp where dp i will store the least number of perfect square numbers that sum up to i Initially we can set all the elements of the dp array to Infinity except the first element which will be This is because if n is then there are no perfect squares that sum up to it and if n is then the least number of perfect squares that sum up to it is We can then iterate through all the numbers from to n and for each number i we can check all the perfect squares that are less than or equal to i We can then update the value of dp i as the minimum of dp i and dp i j j where j j is a perfect square less than or equal to i Finally we can return the value of dp n Here is the JavaScript code for the solution function numSquares n const dp Array n fill Infinity dp for let i i lt n i for let j j j lt i j dp i Math min dp i dp i j j return dp n The time complexity of this solution is O n sqrt n and the space complexity is O n Unique PathsProblem DescriptionSuppose you have a m x n grid You can move either down or right at any point in time You are trying to reach the bottom right corner of the grid How many unique paths are there Solution in JavaScriptWe can use dynamic programming to solve this problem We start by initializing a D array dp of size m x n where dp i j represents the number of unique paths to reach the cell at i j We can fill in the first row and first column of the dp array with because there is only one way to reach any cell in the first row or column Then for all other cells the number of unique paths is the sum of the number of unique paths to reach the cell directly above and the cell directly to the left Finally the value of dp m n represents the number of unique paths to reach the bottom right corner of the grid Here s the JavaScript code for the solution function uniquePaths m n const dp Array m fill map gt Array n fill for let i i lt m i for let j j lt n j dp i j dp i j dp i j return dp m n The time complexity of this solution is O m n because we need to fill in each cell of the dp array exactly once The space complexity is also O m n because we are using a D array to store the values of dp |
2023-06-11 11:16:21 |
Apple |
AppleInsider - Frontpage News |
Apple Vision Pro developer kit applications could open in July |
https://appleinsider.com/articles/23/06/11/apple-vision-pro-developer-kit-applications-could-open-in-july?utm_medium=rss
|
Apple Vision Pro developer kit applications could open in JulyDevelopers working on apps for the Apple Vision Pro headset may soon be able to apply for the developer kit with applications likely to open in July Apple Vision ProAt the time of the launch of the mixed reality headset Apple advised it wouldn t be putting the Apple Vision Pro on sale until early However to help foster the creation of apps in advance of the headset s release it would be producing an Apple Vision Pro developer kit that it would offer to a select number of developers Read more |
2023-06-11 11:47:48 |
Apple |
AppleInsider - Frontpage News |
Crime blotter: Finance director at nonprofit used embezzled funds at Apple Store |
https://appleinsider.com/articles/23/06/11/crime-blotter-finance-director-at-nonprofit-used-embezzled-funds-at-apple-store?utm_medium=rss
|
Crime blotter Finance director at nonprofit used embezzled funds at Apple StoreIn the latest Apple Crime Blotter a store is robbed of iPhones by a man with a box on his head iCloud evidence is to be used against a politician and a deputy is accused of pulling a gun on teens The latest in an occasional AppleInsider series looking at the world of Apple related crime Nonprofit executive spent over of embezzled funds at Apple Store Read more |
2023-06-11 11:13:36 |
海外ニュース |
Japan Times latest articles |
Koki Yamaguchi hits grand slam, Roki Sasaki fans 10 in Marines’ win |
https://www.japantimes.co.jp/sports/2023/06/11/baseball/japanese-baseball/marines-carp-yamaguchi-sasaki/
|
chiba |
2023-06-11 20:24:59 |
ニュース |
BBC News - Home |
Three Britons missing after Egypt boat fire |
https://www.bbc.co.uk/news/business-65871310?at_medium=RSS&at_campaign=KARANGA
|
britons |
2023-06-11 11:31:06 |
ニュース |
BBC News - Home |
'Man City among the greatest sides I have seen - but who are yours?' |
https://www.bbc.co.uk/sport/football/65859469?at_medium=RSS&at_campaign=KARANGA
|
x Man City among the greatest sides I have seen but who are yours x Following Manchester City s Treble Phil McNulty reflects on the greatest football sides he has ever seen and asks you for your suggestions |
2023-06-11 11:28:42 |
ニュース |
BBC News - Home |
World Test Championship: Australia beat India in final at The Oval |
https://www.bbc.co.uk/sport/cricket/65867740?at_medium=RSS&at_campaign=KARANGA
|
australia |
2023-06-11 11:51:51 |
コメント
コメントを投稿