1005.K次取反后最大化的数组和
class Solution(object):
def largestSumAfterKNegations(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
index=0
#flip the samllest index every time
for i in range(k):
#find the smallest index
for j in range(len(nums)):
if nums[j]<=nums[index]:
index=j
nums[index]=-nums[index]
return sum(nums)
134. 加油站
class Solution(object):
def canCompleteCircuit(self, gas, cost):
"""
:type gas: List[int]
:type cost: List[int]
:rtype: int
"""
#start_index
start = 0
#current sum of gas
curSum = 0
#total sum of gas
totalSum = 0
for i in range(len(gas)):
curSum += gas[i] - cost[i]
totalSum += gas[i] - cost[i]
#if current usm of gas is smaller than 0, use next stop as start.
if curSum < 0:
curSum = 0
start = i + 1
#if total sum of gas is smaller than 0, the car must not reach goal
if totalSum < 0: return -1
#else we can return the result
return start
135. 分发糖果
class Solution(object):
def candy(self, ratings):
"""
:type ratings: List[int]
:rtype: int
"""
#candy to give
candyVec = [1] * len(ratings)
#loop from left
for i in range(1, len(ratings)):
#if ranking of right is higher, give one more candy
if ratings[i] > ratings[i - 1]:
candyVec[i] = candyVec[i - 1] + 1
#loop from right
for j in range(len(ratings) - 2, -1, -1):
#if ranking of left is higher, give one more candy
if ratings[j] > ratings[j + 1]:
candyVec[j] = max(candyVec[j], candyVec[j + 1] + 1)
#we have a complete result
return sum(candyVec)