题目描述
Say you have an array for which the i th element is the price of a given stock on day i.
If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.
//刚开始想用动态规划或者深搜,后来用两层循环解决了
public class Solution {public int maxProfit(int[] prices) {int maxsum=0; //最大利润for(int i=0;i<prices.length;i++){int tmpmax=0;//每一趟的最大利润for(int j=i+1;j<prices.length;j++){if(prices[j]>prices[i]){if((prices[j]-prices[i])>tmpmax)tmpmax=prices[j]-prices[i];}}if(maxsum<tmpmax)maxsum=tmpmax;//遍历所有的找到最大利润}return maxsum;}
}