刷leetcode小记2——array(122)

来源:互联网 发布:人力资源分析软件 编辑:程序博客网 时间:2024/06/05 17:49

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.

public class Solution {  
    public int maxProfit(int[] prices) {  
        if (prices.length ==0 ) return 0;  
        int minPrice = prices[0];  
        int maxGap = 0;  
        for (int i = 1; i < prices.length; ++i) {  
            if(prices[i] - minPrice > maxGap) {  
                maxGap = prices[i] - minPrice;  
            }  
            if (prices[i] < minPrice) {  
                minPrice = prices[i];  
            }  
        }  
        return maxGap;  
    }  
}  

先看第一道题,这道题的关键点在于只有一次交易的过程,所以我们首先设置第一个数为最小,profit为0。然后每次用下一个来减去这个最小的数更新profit的值,如果遇到比最小的数更小的数我们就更新一下最小的数。


Say you have an array for which the ith element is the price of a given stock on day i.

Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

public class Solution {
    public int maxProfit(int[] prices) {
        int pro = 0;
        if(prices == null){
            return pro;
        }
        
        for(int i =1; i < prices.length; i++){
          if(prices[i-1] < prices[i]){
              pro += prices[i] - prices[i-1];
          } 
        }
        return pro;
    }
}

0 0