GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — coding-problems/Dynamic Programming/split_coins.py at master · Avangarde2225/coding-problems Expand file tree/ Copy pathsplit_coins.pyMore file actions 53 lines (39 loc) · 1.28 KB / Copy pathsplit_coins.pyFile metadata and controls53 lines (39 loc) · 1.28 KB 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 ''' Split Coins You have a number of coins with various amounts. You need to split the coins in two groups so that the difference between those groups in minimal. Input: [1, 1, 1, 3, 5, 10, 18] Output: 1 Output explanation: First group 1, 3, 5, 10 (or 1, 1, 3, 5, 10) and second group 1, 1, 18 (or 1, 18). ========================================= Simple dynamic programming solution. Find the closest sum to the half of the sum of all coins. Time Complexity: O(C*HS) , C = number of coins, HS = half of the sum of all coins Space Complexity: O(HS) ''' ############ # Solution # ############ def split_coins(coins): if len(coins) == 0: return -1 full_sum = sum(coins) half_sum = full_sum // 2 + 1 dp = [False]*half_sum dp[0] = True for c in coins: for i in range(half_sum - 1, -1, -1): if (i >= c) and dp[i - c]: # if you want to find coins, save the coin here dp[i] = c dp[i] = True for i in range(half_sum - 1, -1, -1): if dp[i]: # if you want to print coins, while i>0: print(dp[i]) i -= dp[i] return full_sum - 2 * i # not possible return -1 ########### # Testing # ########### # Test 1 # Correct result => 1 print(split_coins([1, 1, 1, 3, 5, 10, 18])) |
| You are visitor 01402792 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |