题目描述
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.
解题思路:
有一个b记录买, s记录卖; b是负数,越大越好; s是正数,越大越好
public class Solution {
public int maxProfit(int[] prices) {
int b = Integer.MIN_VALUE;
int s = 0;
for (int i = 0; i < prices.length; i++) {
b = Math.max(b, -prices[i]);
s = Math.max(s, b + prices[i]);
}
return s;
}
}