贪心+前缀和解决连续数组问题
贪心算法 + 前缀和
class Solution { public int findMaxLength(int[] nums) { int len = nums.length; if(len <= 1){ return 0; } //前缀和 int count = 0; //进行更新的 int maxLen = 0; //哈希表记录前缀和对应的索引 HashMap<Integer, Integer> index = new HashMap<>(); //在索引为0之前默认为0 index.put(0, -1); for(int i = 0; i < len; i++){ if(nums[i] == 1) count++; if(nums[i] == 0) count--; //如果包含数值为0的前缀和,说明可以连续在一起,maxLen进行比较更新 if(index.containsKey(count)){ maxLen = Math.max(maxLen, i - index.get(count)); }else{ //放入哈希表中 index.put(count, i); } } return maxLen; } }
美团笔试
import java.io.*; public class Main{ public static void main(String[] args) throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(br.readLine().trim()); char[] ef = br.readLine().trim().toCharArray(); int max = 0, sum = 0; for(int i = 0; i < n; i++){ if(ef[i] == 'E') sum++; if(ef[i] == 'F') sum--; max = Math.max(max, sum); sum = Math.max(sum, 0); } System.out.println(max); } }