动态规划--Leetcode121.买卖股票的最佳时机
給定一個數組,它的第?i 個元素是一支給定股票第 i 天的價格。
如果你最多只允許完成一筆交易(即買入和賣出一支股票),設計一個算法來計算你所能獲取的最大利潤。
注意你不能在買入股票前賣出股票。
示例 1:
輸入: [7,1,5,3,6,4]
輸出: 5
解釋: 在第 2 天(股票價格 = 1)的時候買入,在第 5 天(股票價格 = 6)的時候賣出,最大利潤 = 6-1 = 5 。
? ? ?注意利潤不能是 7-1 = 6, 因為賣出價格需要大于買入價格。
示例 2:
輸入: [7,6,4,3,1]
輸出: 0
解釋: 在這種情況下, 沒有交易完成, 所以最大利潤為 0。
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock
著作權歸領扣網絡所有。商業轉載請聯系官方授權,非商業轉載請注明出處。
public class Solution121 {
?? ?public static int maxProfit(int[] prices) {
? ? ? ? int i,j=0,k=0;
? ? ? ? int n = prices.length;
? ? ? ? int min = 10000;
? ? ? ? int max = -1;
? ? ? ? int t=0,flag;
? ? ? ? for(i=0;i<n;i++)
? ? ? ? {
? ? ? ? ?? ?flag = 0;
? ? ? ? ?? ?if(prices[i]>=max)
? ? ? ? ?? ?{
? ? ? ? ?? ??? ?max = prices[i];
? ? ? ? ?? ??? ?flag = 1;
? ? ? ? ?? ??? ?j = i;
? ? ? ? ?? ??? ?if(j==0)
? ? ? ? ?? ??? ?{
? ? ? ? ?? ??? ??? ?max = -1;
? ? ? ? ?? ??? ?}
? ? ? ? ?? ?}
? ? ? ? ?? ?if(prices[i]<=min)
? ? ? ? ?? ?{
? ? ? ? ?? ??? ?min = prices[i];
? ? ? ? ?? ??? ?flag = 1;
? ? ? ? ?? ??? ?k = i;
? ? ? ? ?? ?}
? ? ? ? ?? ?if(i>0&&flag==1&&k<j&&t<(max-min))
? ? ? ? ?? ?{
? ? ? ? ?? ??? ?t = max - min;
? ? ? ? ?? ?}
? ? ? ? ?? ?if(prices[i]-min>t&&k<i)
? ? ? ? ?? ?{
? ? ? ? ?? ??? ?t = prices[i]-min;
? ? ? ? ?? ?}
? ? ? ? }
? ? ? ? return t;
? ? }
?? ?
?? ?public static void main(String[] args)
?? ?{
?? ?//?? ?int[] a={7,1,5,3,6,4};
?? ?//?? ?int[] a={7,6,4,3,1};
?? ?//?? ?int[] a={2,1,2,1,0,1,2};
?? ??? ?int[] a={3,3,5,0,0,3,1,4};
?? ??? ?System.out.println(maxProfit(a));
?? ?}
}
?
總結
以上是生活随笔為你收集整理的动态规划--Leetcode121.买卖股票的最佳时机的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Leetcode--3. 无重复字符的最
- 下一篇: Leetcode--442. 数组中重复