题目:
Say you have an array for which the ith 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.
思路:
1.目标是求数组中的某两个值的差(最大差值),前提是大的数在小的数后面
2.循环遍历数组,设置一个当前最小值min(初始为Integer.MAX_VALUE)和一个最大差值max(初始化为0)
每次更新min,并更新max(当前元素值-min)
public class Solution {public int maxProfit(int[] prices) {int len=prices.length; //数组长度int max=0; //最大差值int min=Integer.MAX_VALUE; //当前最小值for(int i=0;imax)max=prices[i]-min;}return max;}
}