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)
文章包含三个编程问题的解决方案:1)给定一个数组和K次取反操作,如何最大化数组和;2)在加油站的路径规划问题,判断汽车能否完成一圈;3)分发糖果问题,确保评价高的人至少获得的糖果数不少于评价低的人。每个问题都涉及数组处理和优化策略。
480

被折叠的 条评论
为什么被折叠?



