upd
This commit is contained in:
12
algorithms/labs/lab8/code/greedy/1.py
Normal file
12
algorithms/labs/lab8/code/greedy/1.py
Normal file
@@ -0,0 +1,12 @@
|
||||
def max_profit(prices):
|
||||
profit = 0
|
||||
for i in range(1, len(prices)):
|
||||
if prices[i] > prices[i - 1]:
|
||||
profit += prices[i] - prices[i - 1]
|
||||
return profit
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
print(max_profit([7, 1, 5, 3, 6, 4]))
|
||||
print(max_profit([1, 2, 3, 4, 5]))
|
||||
print(max_profit([7, 6, 4, 3, 1]))
|
||||
16
algorithms/labs/lab8/code/greedy/2.py
Normal file
16
algorithms/labs/lab8/code/greedy/2.py
Normal file
@@ -0,0 +1,16 @@
|
||||
def can_complete_circuit(gas, cost):
|
||||
if sum(gas) < sum(cost):
|
||||
return -1
|
||||
start = 0
|
||||
bal = 0
|
||||
for i in range(len(gas)):
|
||||
bal += gas[i] - cost[i]
|
||||
if bal < 0:
|
||||
start = i + 1
|
||||
bal = 0
|
||||
return start
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
print(can_complete_circuit([1, 2, 3, 4, 5], [3, 4, 5, 1, 2]))
|
||||
print(can_complete_circuit([2, 3, 4], [3, 4, 3]))
|
||||
22
algorithms/labs/lab8/code/greedy/3.py
Normal file
22
algorithms/labs/lab8/code/greedy/3.py
Normal file
@@ -0,0 +1,22 @@
|
||||
from functools import cmp_to_key
|
||||
|
||||
|
||||
def largest_number(nums):
|
||||
arr = list(map(str, nums))
|
||||
|
||||
def cmp(a, b):
|
||||
if a + b < b + a:
|
||||
return 1
|
||||
if a + b > b + a:
|
||||
return -1
|
||||
return 0
|
||||
|
||||
arr.sort(key=cmp_to_key(cmp))
|
||||
res = "".join(arr)
|
||||
return "0" if res[0] == "0" else res
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
print(largest_number([10, 2]))
|
||||
print(largest_number([3, 30, 34, 5, 9]))
|
||||
print(largest_number([0, 0]))
|
||||
Reference in New Issue
Block a user