funcnumRescueBoats(people []int, limit int)int { sort.Ints(people) n := len(people) left, right := 0, n-1 ans := 0 for left <= right { if people[left]+people[right] <= limit { left++ } right-- ans++ } return ans }
funccountBattleships(board [][]byte)int { ans := 0 for i, b := range board { for j, b2 := range b { if b2 == 'X' && (i == 0 || board[i-1][j] == '.') && (j == 0 || board[i][j-1] == '.') { ans++ } } } return ans }
funcmaxScore(nums []int, x int)int64 { n := len(nums) memo := make([][2]int, n) for i := range memo { memo[i] = [2]int{-1, -1} } var dfs func(int, int)int dfs = func(i int, j int) (res int) { if i == n { return } if memo[i][j] != -1 { return memo[i][j] } if nums[i]%2 != j { res = dfs(i+1, j) } else { res = max(dfs(i+1, j), dfs(i+1, j^1)-x) + nums[i] } memo[i][j] = res return res } returnint64(dfs(0, nums[0]%2)) }
记忆化搜索:
1 2 3 4 5 6 7 8 9 10 11
funcmaxScore2(nums []int, x int)int64 { n := len(nums) dp := make([][2]int, n+1) for i := n - 1; i >= 0; i-- { v := nums[i] r := v % 2 dp[i][r^1] = dp[i+1][r^1] // 奇偶性不同 dp[i][r] = max(dp[i+1][r], dp[i+1][r^1]-x) + v } returnint64(dp[0][nums[0]%2]) }
funcmaximumBeauty(nums []int, k int)int { n := len(nums) sort.Ints(nums) d := make([]int, nums[n-1]+k+2) for _, num := range nums { d[max(0, num-k)] += 1 d[num+k+1] -= 1 } sum := 0 ans := 0 for i := max(0, nums[0]-k); i < len(d); i++ { sum += d[i] ans = max(ans, sum) } return ans }
funcmaximumBeauty(nums []int, k int)int { n := len(nums) sort.Ints(nums) left, ans := 0, 1 for right := 1; right < n; right++ { if nums[right]-nums[left] > k*2 { left++ } ans = max(ans, right-left+1) } return ans }