class Solution {
public int largestRectangleArea(int[] heights) {
int n=heights.length;
//中心拓展方法
int sum=0;
Stack<Integer>s=new Stack<>();
for(int i=0;i<n;i++){
int count=1;
int left=i-1;
int right=i+1;
while(left>=0&&s.peek()=heights[i]){
left--;
count++;
}
while(right<n&&s.peek()>=heights[i]){
right++;
count++;
}
sum=Math.max(sum,heights[i]*count);
}
return sum;
}
}
class Solution {
public int largestRectangleArea(int[] heights) {
int n = heights.length;
Deque<Integer> st = new ArrayDeque<>();
st.push(-1); // 在栈中只有一个数的时候,栈顶的「下面那个数」是 -1,对应 left[i] = -1 的情况,表示他的右边界-左边界值
int ans = 0;
for (int right = 0; right <= n; right++) {
int h = right < n ? heights[right] : -1;
while (st.size() > 1 && h <= heights[st.peek()]) {
int i = st.pop(); // 矩形的高(的下标)
int left = st.peek(); // 栈顶下面那个数就是 left
ans = Math.max(ans, heights[i] * (right - left - 1));
}
st.push(right);
}
return ans;
}
}
public int canCompleteCircuit(int[] gas, int[] cost) {
int n=gas.length;
//仅考虑从加油站的净收益即可
int[]dif=new int[n];
int sum=0;
for(int i=0;i<n;i++){
dif[i]=gas[i]-cost[i];
}
//从不同起点出发
for(int i=0;i<n;i++){
int count=0;
//假如使用一个变量step表示当前走了多少步
int step=0;
for( ;step<n;step++){
//每次的差值
count+=dif[(i+step)%n];
//假如道路中间变成负数,就无法到达
if(count<0){i=i+step;break;}
}
if(count>=0)return i;
}
return -1;
}
牛客.abb(hard 动态规划+哈希表)
像是动态规划,a,b点-结合一个子序列
以i为结尾的所有的子序列
复制代码
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n=in.nextInt();
String aa=in.next();
char[]a=aa.toCharArray();
int []f=new int[26];
int []g=new int[26];
int []dp=new int[26];
long sum=0;
for(int i=0;i<n;i++){
int x=a[i]-'a';
dp[x]=f[x];
sum+=dp[x];
f[x]=f[x]+i-g[x];
g[x]=g[x]+1;
}
System.out.print(sum);
}
牛客.哈夫曼编码
什么是哈夫曼编码
压缩存储
abbcccdd 二进制。使用二进制来存储,先对出现的字符进行编码
比如
a:0
b:01
c:001
d:11
那么长长的字符串由字符串表示的话,就可以非常省空间,但是会出现问题,就像是滑动窗口的漏包 比如001 : ab 或者c,这样就有歧义了,说明这种编码是不合理的,即错误的
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n=in.nextInt();
PriorityQueue<Long>q=new PriorityQueue<>();
for(int i=0;i<n;i++){
q.add(in.nextLong());
}
long sum=0;
while(q.size()>1){
long x=q.poll();
long y=q.poll();
q.add(x+y);
sum+=x+y;
}
System.out.print(sum);
}