题目:给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。如果你最多只允许完成一笔交易(即买入和卖出一支股票),设计一个算法来计算你所能获取的最大利润。注意你不能在买入股票前卖出股票。
解题思路:双指针,左指针记录最小值,右指针依次后移
classSolution{publicintmaxProfit(int[] prices){int len = prices.length;if(len==0)return0;int left =0;int right =1;int max =0;while(right<len){if(prices[left]>=prices[right]){
left = right;
right = left+1;}else{if(prices[right]-prices[left]>max){
max = prices[right]-prices[left];}
right++;}}return max;}}