最值问题的第三种思路: Sliding window类的题
-》类似maximum subarray
当遇到不满足条件的点时,更新left bound,并且要清空之前累计的结果:maximum subarray把和清0,此题把新的左边界之前的元素全部remove掉(原来左边界之后)
public class Solution {
public int lengthOfLongestSubstring(String s) {
if (s == null || s.length() == 0) return 0;
HashSet<Character> set = new HashSet<>();
int leftbound = 0;
int max = 0;
int submax = 0;
for (int i = 0; i < s.length(); i++) {
if (!set.contains(s.charAt(i))) {
set.add(s.charAt(i));
submax++;
max = Math.max(max, submax);
} else {
while (s.charAt(i) != s.charAt(leftbound)) {
set.remove(s.charAt(leftbound));
leftbound++;
}
leftbound++;
submax = i - leftbound + 1;
}
}
return max;
}
}
再看看maximum subarray:
//用DP做,空间O(n) 不是最优
//怎么改进呢?-》看递推式 >0的时候就加上,小于0的时候,相当于dp[i-1]置0
public class Solution {
public int maxSubArray(int[] A) {
if (A == null && A.length == 0) return 0;
int submax = A[0];
int max = A[0];
for (int i = 1; i < A.length; i++) {
if (submax > 0) {
submax += A[i];
} else {
submax = A[i];
}
max = Math.max(max, submax);
}
return max;
}
}