Best Time to Buy and Sell Stock

来源:互联网 发布:方正数据库免费入口 编辑:程序博客网 时间:2024/04/29 21:20

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.



#include<stdio.h>int maxProfit(int *prices, int n) {    int i = 0;    int profit = 0, min = prices[0];    if(n == 0) return 0;    for(i = 1; i < n; i++){        if(prices[i] - min > profit) profit = prices[i] - min;        if(prices[i] < min) min = prices[i];    }    return profit;}void main() {    int prices[] = {7,6,5,4,3,2,1,0};    int n = 8;    printf("%d\n", maxProfit(prices, n));}


0 0
原创粉丝点击