新农上路
- 积分
- 99
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2011-11-7
- 最后登录
- 1970-1-1
|
做了下第二题,欢迎指正。求米
- # coding: utf-8
- """
- Given an array containing only 0 and 1s, find the best subarray to perform a single flip operation.
- The goal is that: after the flip, number of 1s should be the maximum.
- Flip operation means that you will convert all 0 to 1, and all 1 to 0 in that array.
- You can skip flipping if you think it is not worth doing the flip.
- Return the maximum number of 1s after you do the flip.
- 队友还是用的prefix sum再找区间最大的差值,面试官说可以O(1)空间,作为homework。
- Follow-up: what if it is a 2D array?</div>
- """
- class Solution:
- def max_flip(self, bits):
- dp = [0] * len(bits)
- for i, b in enumerate(bits):
- val = 1 if b == '1' else -1
- prev = dp[i - 1] if i > 0 else 0
- dp[i] = min(prev + val, val)
- orig_one_count = sum(1 for b in bits if b == '1')
- res = orig_one_count + max(-min(dp), 0)
- return res
- def max_flip_follow_up(self, bits):
- # O(1) space. rolling array. dp[i] only relies on the prev one.
- dp = [0] * 2
- min_dp = 0
- for i, b in enumerate(bits):
- val = 1 if b == '1' else -1
- prev = dp[(i - 1) % 2] if i > 0 else 0
- dp[i % 2] = min(prev + val, val)
- min_dp = min(min_dp, dp[i % 2])
- orig_one_count = sum(1 for b in bits if b == '1')
- res = orig_one_count + max(-min_dp, 0)
- return res
-
- import unittest
- class Tests(unittest.TestCase):
- def test1(self):
- bits = '0001000'
- sol = Solution()
- actual = sol.max_flip(bits)
- self.assertEqual(actual, 6)
- actual2 = sol.max_flip_follow_up(bits)
- self.assertEqual(actual2, 6)
- def test2(self):
- bits = '1001001'
- sol = Solution()
- actual = sol.max_flip(bits)
- self.assertEqual(actual, 6)
- actual2 = sol.max_flip_follow_up(bits)
- self.assertEqual(actual2, 6)
- def test3(self):
- bits = '1111111'
- sol = Solution()
- actual = sol.max_flip(bits)
- self.assertEqual(actual, 7)
- actual2 = sol.max_flip_follow_up(bits)
- self.assertEqual(actual2, 7)
- def test4(self):
- bits = '1010101'
- sol = Solution()
- actual = sol.max_flip(bits)
- self.assertEqual(actual, 5)
- actual2 = sol.max_flip_follow_up(bits)
- self.assertEqual(actual2, 5)
- unittest.main(verbosity=2)
复制代码 |
|