|
| 1 | +package com.stevesun.solutions; |
| 2 | + |
| 3 | +/** |
| 4 | + * In the computer world, use restricted resource you have to generate maximum benefit is what we always want to pursue. |
| 5 | +
|
| 6 | + For now, suppose you are a dominator of m 0s and n 1s respectively. On the other hand, there is an array with strings consisting of only 0s and 1s. |
| 7 | +
|
| 8 | + Now your task is to find the maximum number of strings that you can form with given m 0s and n 1s. Each 0 and 1 can be used at most once. |
| 9 | +
|
| 10 | + Note: |
| 11 | +
|
| 12 | + The given numbers of 0s and 1s will both not exceed 100 |
| 13 | + The size of given string array won't exceed 600. |
| 14 | +
|
| 15 | + Example 1: |
| 16 | +
|
| 17 | + Input: Array = {"10", "0001", "111001", "1", "0"}, m = 5, n = 3 |
| 18 | + Output: 4 |
| 19 | +
|
| 20 | + Explanation: This are totally 4 strings can be formed by the using of 5 0s and 3 1s, which are “10,”0001”,”1”,”0” |
| 21 | +
|
| 22 | + Example 2: |
| 23 | +
|
| 24 | + Input: Array = {"10", "0", "1"}, m = 1, n = 1 |
| 25 | + Output: 2 |
| 26 | +
|
| 27 | + Explanation: You could form "10", but then you'd have nothing left. Better form "0" and "1". |
| 28 | +
|
| 29 | + */ |
| 30 | +public class OnesandZeroes { |
| 31 | + |
| 32 | + public int findMaxForm(String[] strs, int m, int n) { |
| 33 | + int[][] dp = new int[m+1][n+1]; |
| 34 | + for (String str : strs){ |
| 35 | + int[] count = count(str); |
| 36 | + for (int i = m; i >= count[0]; i--){ |
| 37 | + for (int j = n; j >= count[1]; j--){ |
| 38 | + dp[i][j] = Math.max(dp[i][j], dp[i - count[0]][j - count[1]] + 1); |
| 39 | + } |
| 40 | + } |
| 41 | + } |
| 42 | + return dp[m][n]; |
| 43 | + } |
| 44 | + |
| 45 | + private int[] count(String str) { |
| 46 | + int[] count = new int[]{}; |
| 47 | + for (char c : str.toCharArray()){ |
| 48 | + count[c - '0']++; |
| 49 | + } |
| 50 | + return count; |
| 51 | + } |
| 52 | + |
| 53 | +} |
0 commit comments