您的位置:首页 > 编程语言 > Java开发

Best Time to Buy and Sell Stock (Java)

2015-01-17 17:19 183 查看
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.

注意,买入的日期一定是早于卖出的日期,所以遍历数组时,维护一个max代表收益,min记录当前最小值。

Source

public class Solution {
public int maxProfit(int[] prices) {
int max = 0, min = Integer.MAX_VALUE;

for(int i = 0; i < prices.length; i++){
min = Math.min(min, prices[i]);
max = Math.max(max, prices[i] - min);
}
return max;
}
}

Test

public static void main(String[] args){

int[] prices = {4,1,2,3};

int a = new Solution().maxProfit(prices);

System.out.println(a);

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  LeetCode