1. Maximize Sum Of Array After K Negations (Leetcode Number: 1005)
Sort the original list -> convert as many negative elements as the amount is smaller or equal to given k -> if the value of k is bigger than the number of negative elements, get the total sum first and deal with the current minimum element accordingly.
class Solution:
def largestSumAfterKNegations(self, nums: List[int], k: int) -> int:
sort_nums = sorted(nums)
i, min_val, sum_val, res = 0, 0, 0, 0
while i < len(nums) and i < k and sort_nums[i] < 0:
sort_nums[i] *= -1
i += 1
sum_val = sum(sort_nums)
if (k - i) % 2 == 1:
min_val = min(sort_nums)
res = sum_val - min_val * 2
else:
res = sum_val
return res
2. Gas Station (Leetcode Number: 134)
Check the condition, "If there exists a solution, it is guaranteed to be unique". Therefore the next element of the last element that gas[i] - cost[i] is smaller than 0 would be the unique solution.
class Solution:
def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:
cur_sum = 0
total_sum = 0
res = 0
n = len(gas)
for i in range(n):
cur_sum += gas[i] - cost[i]
total_sum += gas[i] - cost[i]
if cur_sum < 0:
cur_sum = 0
res = i + 1
if total_sum >= 0:
return res
else:
return -1
3. Candy (Leetcode Number: 135)
Using 2 arrays, the first one traverse from left to right (Working on the condition that when right element is bigger than the element sits on the left of itself) and the second on traverse from right to left (Working on the condition that when left element is bigger than the element sits on the right of itself). The array used in the second loop is the result of the first loop, therefore the final value of this element has to be the bigger one comparing the current value with the value of the right element (when left value > right value).
class Solution:
def candy(self, ratings: List[int]) -> int:
n = len(ratings)
candy = [1] * n
for i in range(1, n):
if ratings[i] > ratings[i - 1]:
candy[i] = candy[i - 1] + 1
for j in range(n - 2, -1, -1):
if ratings[j] > ratings[j + 1]:
candy[j] = max(candy[j], candy[j + 1] + 1)
return sum(candy)