GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — coding-problems/Dynamic Programming/split_coins.py at master · viterbox/coding-problems

Expand file tree

/

split_coins.py

Copy path
More file actions
More file actions

Latest commit

 

History

History
History
53 lines (39 loc) · 1.28 KB
/

split_coins.py

Copy path

File metadata and controls

53 lines (39 loc) · 1.28 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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.