做自媒体那几个网站好点,wordpress无法寻找图像,时网站建设公司管理,电子政务网站建设总结问题描述#xff1a;给定一个整数数组prices#xff0c;其中第i各元素代表了第i填的股票价格#xff1b;非负整数fee代表了交易股票是的手续费用#xff0c;你可以无限次的完成交易#xff0c;但是你眉笔交易都需要付手续费#xff0c;如果你已经购买了一个股票#xff…问题描述给定一个整数数组prices其中第i各元素代表了第i填的股票价格非负整数fee代表了交易股票是的手续费用你可以无限次的完成交易但是你眉笔交易都需要付手续费如果你已经购买了一个股票在卖出它之前不能再继续购买股票了返回获得利润的最大值。注意一次交易是指买入持有并卖出股票的整个过程你就不能再继续购买股票了。并定义卖股票才可以进行扣费。
动态规划求解定义动态数组dp[i][0]表示第i天手里没有股票的最大值此时有两种选择一种是dp[i-1][1]prices[i]-2表示在第i天卖出了股票获得了第i天的利润第二种是不改变与之前相同dp[i-1],dp[i][1]表示第i天手里有股票的最大值此时有两种选择dp[i-1][0]-prices[i]或者保持dp[i-1][0]
public int maxProfit(int []prices)
{
int [][]dpnew int[prices.length][2];dp[0][0]0;
dp[0][1]-prices[0];
for(int i0;iprices.length;i)
{
dp[i][0]Math.max(dp[i-1][0],dp[i-1][1]prices[i]-2);
dp[i][1]Math.max(dp[i-1][1],dp[i-1][0]-prices[i]);
}
return Math.max(dp[prices.length-1][0],dp[prices.length-1][1]);
}
递归方式求解对于每一天而言如果手上持有股票可以选择卖或者不卖然后进入下一天中 如果手上没有股票则可以选择不买或者买然后进入下一年中最后到达最后一天对将利润加入PriorityQueueInteger maxheapnew PriorityQueue((a,b)-{return b-a;})或者(PriorityQueueIntegermaxheapnew PriorityQueue(Collections.reverseOrder()))最大堆中最后从最大堆中弹出第一个数字即为最大利润
private getMaxProfit(int [] prices,int index,int profit,Boolean ishasone,PriorityQueueInteger queue)
{
if(indexprices.length)
{
queue.add(profit);
return;
}
if(ishasone)
{
getMaxProfit(prices,index1,profit,ishasone);
getMaxProfit(prices,index1,profitprices[i]-2,!ishasone)
}else
{
getMaxProfit(prices,index1,profit-prices[i],!ishasone);
getMaxProfit(prices,index1,profit,ishasone)
}
}public int GetMaxProfit(int []prices)
{
PriorityQueueIntegermaxheapnew PriorityQueue(Collections.reverseOrder());
getMaxProfit(prices,0,0,false);
return maxheap.peek();
} 知识点总结最小堆定义PriorityQueueIntegerminHeapnew PriorityQueue();最大堆定义1 PriorityQueueIntegermaxHeapnew PriorityQueue(Collections.reverseOrder());PriorityQueueIntegerminheapnew PriorityQueue((a,b)-{return b-a});最大堆定义3PriorityQueueIntegermaxHeapnew PriorityQueue(new ComparableInteger(){ Override public int Compare(Integer t1,Integer t2) { return t2-t1; } }); PriorityQueue增加操作minHeap.add(),minheap.offer() PriorityQueue减少操作minheap.poll(),minheap.remove();会弹出 PriorityQueue查询操作:minheap.peek();
Map知识点MapInteger,Integermapnew HashMapInteger,Integermap; 增加:Map.put(key,value); 访问:Map.get(key); 删除;Map.remove(key); 遍历 for (Integer i : Sites.keySet()) { System.out.println(key: i value: Sites.get(i)); } // 返回所有 value 值 for(String value: Sites.values()) { // 输出每一个value System.out.print(value , );