Leetcode 1783 Solution
This article provides solution to leetcode question 1783 (ways-to-make-a-fair-array)
Access this page by simply typing in "lcs 1783" in your browser address bar if you have bunnylol configured.
Leetcode Question Link
https://leetcode.com/problems/ways-to-make-a-fair-array
Solution
class Solution:
def waysToMakeFair(self, nums: List[int]) -> int:
total = sum(nums)
ans = 0
dp1 = [0] * len(nums)
for i in range(len(nums)):
dp1[i] = dp1[i - 1] if i > 0 else 0
if i % 2 == 0:
dp1[i] += nums[i]
dp2 = [0] * len(nums)
for i in range(len(nums) - 1, -1, -1):
dp2[i] = dp2[i + 1] if i < len(nums) - 1 else 0
if i % 2 == 1:
dp2[i] += nums[i]
for i in range(len(nums)):
left_sum = dp1[i - 1] if i > 0 else 0
right_sum = dp2[i + 1] if i < len(nums) - 1 else 0
if (left_sum + right_sum) * 2 + nums[i] == total:
ans += 1
return ans