贪心算法求解最大数代码
时间: 2024-05-13 18:12:45 浏览: 11
贪心算法是一种常见的算法思想,它通常用于求解最优化问题。对于求解最大数问题,贪心算法可以从高位开始,每次选择当前位上可以取到的最大数字,直到所有位都被填满,得到的即为最大数。
以下是一个使用贪心算法求解最大数的代码实现:
```python
def findMaxNum(nums):
if not nums:
return ""
nums = [str(num) for num in nums]
nums.sort(key=lambda x: x * 3, reverse=True)
return str(int(''.join(nums)))
# Example usage:
nums = [10, 2]
print(findMaxNum(nums)) # Output: "210"
```
这个算法的基本思路是将所有数字转化为字符串,并按照每个数字重复三次的字符串大小进行比较。这样可以确保对于每个数字,它都可以被正确地放在它应该出现的位置上。
相关问题
贪心算法求解背包问题代码
以下是一种用贪心算法解决背包问题的代码示例(使用 Python 语言):
```
def knapsack(items, maxweight):
"""
Solve the knapsack problem by finding the most valuable
subsequence of `items` subject that weighs no more than
`maxweight`.
`items` is a list of pairs `(value, weight)`, where `value` is
a number and `weight` is a non-negative integer.
`maxweight` is a non-negative integer.
Returns a pair whose first element is the sum of values in the most
valuable subsequence, and whose second element is the subsequence.
"""
# Order items by value-to-weight ratio
items = sorted(items, key=lambda x: x[0]/x[1], reverse=True)
knapsack = []
total_value = 0
total_weight = 0
for value, weight in items:
if total_weight + weight <= maxweight:
knapsack.append((value, weight))
total_value += value
total_weight += weight
return total_value, knapsack
# Example usage
items = [(4, 12), (2, 1), (6, 4), (1, 1), (2, 2)]
maxweight = 15
value, knapsack = knapsack(items, maxweight)
print("The maximum value of items in the knapsack is", value)
print("The items in the knapsack are", knapsack)
```
该代码使用贪心策略,将物品按照价值-重量比从高到低排序,依次选取能放入背包中的物品。最终得到背包中物品的最大价值和物品组成。
贪心算法求解免费馅饼问题代码
免费馅饼问题是一个著名的贪心算法问题,下面是一个 Python 代码示例:
```python
def max_pancakes(pancakes, hunger):
# 将馅饼按照美味度从大到小排序
sorted_pancakes = sorted(pancakes, reverse=True)
max_pancakes = 0
for pancake in sorted_pancakes:
if hunger >= pancake:
# 如果还有胃口,就吃掉这个馅饼
max_pancakes += 1
hunger -= pancake
else:
# 否则就停止吃馅饼
break
return max_pancakes
# 示例用法
pancakes = [1, 3, 2, 4, 5]
hunger = 7
print(max_pancakes(pancakes, hunger)) # 输出 3
```
代码中的 `max_pancakes` 函数接受一个馅饼列表和一个胃口值作为参数,返回能够吃掉的最大馅饼数。函数首先将馅饼按照美味度从大到小排序,然后依次尝试吃掉每个馅饼。如果还有胃口,就吃掉这个馅饼并将已吃掉的馅饼数加 1,否则就停止吃馅饼。最后返回已吃掉的馅饼数。