best-time-to-buy-and-sell-stock Java code

来源:互联网 发布:linux黑客帝国代码雨 编辑:程序博客网 时间:2024/05/17 22:55

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.

import java.util.*;public class Solution {    public int maxProfit(int[] prices) {        if(prices.length<2){            return 0;        }        int maxProfit=0;        int temp = prices[0];        for(int i=1; i<prices.length; i++){            temp = Math.min(temp, prices[i]);            maxProfit = Math.max(maxProfit, prices[i]-temp);            }        return maxProfit;    }}