1005.K次取反后最大化的数组和
class Solution(object):
def largestSumAfterKNegations(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
nums.sort(key=lambda x: abs(x), reverse=True)
for i in range(len(nums)):
if nums[i]<0 and k>0:
nums[i]=-nums[i]
k -= 1
if k%2==1:
nums[-1]=-nums[-1]
return sum(nums)
134.加油站
class Solution(object):
def canCompleteCircuit(self, gas, cost):
"""
:type gas: List[int]
:type cost: List[int]
:rtype: int
"""
i=0
count = 0
result = 0
used=[0 for j in range(len(gas))]
for i in range(len(gas)*2):
if count+gas[i%len(gas)]>=cost[i%len(gas)]:
count += gas[i%len(gas)]-cost[i%len(gas)]
if not used[i%len(gas)]:
used[i%len(gas)]=1
elif result == i%len(gas):
return result
elif count+gas[i%len(gas)]<cost[i%len(gas)]:
count = 0
result = i+1
return -1
class Solution(object):
def canCompleteCircuit(self, gas, cost):
"""
:type gas: List[int]
:type cost: List[int]
:rtype: int
"""
curSum=0
totalSum=0
start=0
for i in range(len(gas)):
curSum += gas[i]-cost[i]
totalSum += gas[i]-cost[i]
if curSum<0:
curSum=0
start=i+1
if totalSum<0:
return -1
return start
135. 分发糖果
class Solution(object):
def candy(self, ratings):
"""
:type ratings: List[int]
:rtype: int
"""
candys = [1 for i in range(len(ratings))]
for j in range(1, len(ratings)):
if ratings[j]>ratings[j-1]:
candys[j]=candys[j-1]+1
for k in range(len(ratings)-2 , -1, -1):
if ratings[k]>ratings[k+1]:
candys[k]=max(candys[k+1]+1, candys[k])
return sum(candys)