LeetCode-best time to buy and sell stock 1 数组
生活随笔
收集整理的這篇文章主要介紹了
LeetCode-best time to buy and sell stock 1 数组
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1.問題
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.
分析:假設你有一個數組,其中第i個元素是一個給定股票第i天的價格。只能進行一次交易,尋找最大利潤。
找到數組中最小的元素與最大的元素,最大值要在最小值之前。
設兩個變量,一個存儲當前找到的最小值,一個存儲當前最大的利潤差值,遍歷數組。
2、解答
public class Solution {public int maxProfit(int[] prices) {int maxout = 0;int min = Integer.MAX_VALUE;for(int i = 0; i<prices.length;i++){if(prices[i]<min)min = prices[i];if(prices[i]-min >maxout)maxout = prices[i] - min;}return maxout;} }?
總結
以上是生活随笔為你收集整理的LeetCode-best time to buy and sell stock 1 数组的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: LeetCode-best time t
- 下一篇: opencv图像前景目标提取