Greedy
๋ฌธ์ ์ด๋ค.
์์ด๋์ด๋ ๋ฐ๋ก ์๊ฐ๋๋ ๋ฌธ์ ์๋ค. ๊ทผ๋ฐ ์ข ํค๋งธ๋ค. ๐ฅ๐ฅ
from collections import deque
# ๋น ํ ๋ง๋ค๊ธฐ
N = int(input())
inputArr = list()
for _ in range(N):
inputArr.append(int(input()))
inputArr.sort()
nums, _sum = deque(inputArr), 0
# plus
while len(nums) >= 2 and nums[-1] > 0:
n2, n1 = nums.pop(), nums.pop()
if n2 <= 0:
nums.append(n1)
nums.append(n2)
break
elif n1 <= 0:
nums.append(n1)
_sum += n2
break
_sum += n1 * n2
# print(_sum, nums)
if nums and nums[-1] > 0:
_sum += nums.pop()
# print('middle', _sum, nums)
# minus
while len(nums) >= 2:
n1, n2 = nums.popleft(), nums.popleft()
_sum += n1 * n2
# print(_sum, nums)
if nums:
_sum += nums.pop()
print(_sum)
์ฝ๋๊ฐ ์์ฃผ์์ฃผ ๋๋ฝ๋ค..
๋จธ๋ฆฌ ์ํ์ ๋์ถฉ ํ๊ณ ๋๊ธฐ๋ ค๊ณ ํ์ง๋ง, ์ฌ๋ฌ ์ฐจ๋ก ํ๋ ธ๋ค.
from collections import deque
N = int(input())
minusArr, plusArr, _sum = list(), list(), 0
for _ in range(N):
n = int(input())
if n > 0:
plusArr.append(n)
else:
minusArr.append(n)
plusArr.sort()
minusArr.sort(reverse=True)
while len(plusArr) >= 2:
n1, n2 = plusArr.pop(), plusArr.pop()
_sum += n1 * n2
if plusArr:
_sum += plusArr.pop()
while len(minusArr) >= 2:
n1, n2 = minusArr.pop(), minusArr.pop()
_sum += n1 * n2
if minusArr:
_sum += minusArr.pop()
print(_sum)
์ด๋ฒ์ ์์
, 0
, ์์
๋ฅผ ๋ด๋ list
๋ฅผ ๋ฐ๋ก ๋ด์์ ํ์๋ค.
๊น๋ํ๊ฒ ํ์๊ณ , ๋น์ฐํ ์ ๋ต์ผ ์ค ์์๋๋ฐ ์๊ฐ์ด๊ณผ
๋ด๋ค.
from collections import deque
N = int(input())
minusArr, plusArr, _sum = list(), list(), 0
for _ in range(N):
n = int(input())
if n > 1:
plusArr.append(n)
elif n == 1:
_sum += 1
else:
minusArr.append(n)
plusArr.sort()
minusArr.sort(reverse=True)
while len(plusArr) >= 2:
n1, n2 = plusArr.pop(), plusArr.pop()
_sum += n1 * n2
if plusArr:
_sum += plusArr.pop()
while len(minusArr) >= 2:
n1, n2 = minusArr.pop(), minusArr.pop()
_sum += n1 * n2
if minusArr:
_sum += minusArr.pop()
print(_sum)
๋์ ํ ๋ฐฉ๋ฒ์ ๋ชฐ๋ผ์ ๋ค๋ฅธ ๋ถ ๋ธ๋ก๊ทธ๋ฅผ ์ฐธ๊ณ ํ๋ค.
1
์ ๋ค๋ฅธ ์ฐ์ฐ ์์ด ๋ฐ๋ก ๋ํด์ผ ๊ฐ์ฅ ํฉ์ด ์ปค์ง๋ค๋ ๊ฒ์ด๋ค.
๐ Try 2
์ฝ๋์์ ํด๋น ๋ถ๋ถ๋ง ์์ ํด์ฃผ๋๊น ๋ง์์ต๋๋ค!!
๊ฐ ๋ด๋ค.